Code Monkey home page Code Monkey logo

qt-widgets's Introduction

Qt-Widgets

A collection of examples and reusable elements created with Qt6 widgets.

Capture

Table of Contents

Purpose

The goal of this repository is to gather a large number of reusable Qt widgets that may be used in any application. By doing so, we avoid having to reinvent the wheel every time we start a new project and can instead focus on adjustments and revisions rather than starting from scratch.

Requirements

For C++ projects you will need:

  • C++14
  • CMake 3.10+
  • Qt6

For Python projects you will need:

  • Python 3.10+
  • Whatever library is mentioned in the project's requirements.txt file.

Compilation

Qt Creator IDE

To create the project, open the appropriate CMakeLists.txt file in Qt Creator.

Terminal

Set the environment variable "CMAKE PREFIX PATH" to the Qt6 installation path.

Open the terminal in the project directory and use the following commands:

Windows:

$ mkdir build
$ cd build
$ cmake ..
$ start ./Qt.project_name.sln

Linux/macOS:

$ mkdir build
$ cd build
$ cmake -GNinja ..
$ ninja ../project_name

PyQt

The recommended approach to launch PyQT projects is to use virtualenv:

$ virtualenv env
$ source env/bin/activate
$ pip install -r requirements.txt
$ python main.py

Use the following snippet to convert .ui files to .py scripts:

from PyQt6 import uic

with open("source.ui") as ui_file:
    with open("output_ui.py","w") as py_ui_file:
        uic.compileUi(ui_file,py_ui_file)

Content

Core

QObject is perhaps the most significant class in the whole Qt ecosystem. It carries with it two enormously important mechanisms:

  1. Slots and signals;
  2. Parent-child relationship.

When subclassing QObject, you must include the Q_OBJECT macro in the declaration.

class SubClass : public QObject {
  Q_OBJECT

public:
  SubClass(QObject *parent = nullptr);
  ~SubClass();

signals:
  void someSignal();

public slots:
  void someSlot();
};
Description Screenshot
Children Generator - Example of parent-child relationship in Qt. The generator may be used to create and delete children on the fly. When the generator instance is destroyed, all of its children are also destroyed.
Custom Signal and Slots - A slot is just a standard method that may be connected to a signal. Many slots can be connected to a single signal. A signal is just a value that may be emitted by any function. When the signal is emitted, the value emitted by the signal is passed as a parameter to all associated slots.

Check out the Python implementation as well.
custom_signal_slots
Smart Pointers - A smart pointer is an abstract data type that has all of the properties of a raw pointer plus automated garbage collection. Qt featured smart pointers long before they were included in C++ standard. These are also used in some of the projects. However, raw pointers are typically used for QObjects since they utilise a parent-child model to manage all issues related to the objects life cycle. smart_pointers
QVariant and QMetaType - The QVariant class serves as a union for the most commonly used Qt data types. Because C++ prohibits unions from containing types with non-default constructors or destructors, the majority of useful Qt classes cannot be used in raw unions. The type is registered via the Q_DECLARE_METATYPE(Type) macro, so that QMetaType can recognize this type. Q_DECLARE_METATYPE expects a class or struct to contain a default constructor, a copy constructor, and a public destructor. qvariant_and_qmetatype

Collections And Algorithms

Qt has implemented a large number of containers and accompanying algorithms that correspond to STL containers and algorithms. Some have been deprecated, such as qSort(), so be careful to read the documentation before using them. This is due to the fact that it was created prior to the standardization of STL containers. Some features, like as the contains() function, were first added in C++20, about 30 years later.

So the obvious issue is whether you should use Qt's containers or STL. The ones from Qt are fully integrated into the Qt APIs, therefore compatibility is an important consideration. There is no obvious winner in terms of efficiency and performance, and both are viable options. The STL, on the other hand, would enable you to design logic independent of the GUI framework, making the transition to another technology much easier.

Description Screenshot
QList - QList is a generic container class in Qt. It keeps a list of values and allows for rapid index-based access as well as quick insertions and deletions. Despite the fact that it is implemented as an array-list, it has very fast prepends and appends. QList is the ideal type to utilize for most purposes. This example shows how to initialize, display, and find and delete the list's elements.

A quick remark for Python programmers: Python lists cannot be serialized using QDataStream, whereas QList can be serialized using C++. When porting the C++ code, QList cannot always be replaced with Python list.
qlist
QList vs QVector - QVector is very similar in use to QList. One distinction is that items of QVector are always stored in a contignous way in memory, whereas QList does not. qlist_vs_qvector
QSet - QSet assures the uniquness of it's elements. Although the order in which the elements are inserted is lost. qset
QMap - The QMap class is a template class that offers a dictionary based on a red-black tree. QMap<Key, T> is a generic container class in Qt. It holds (key, value) pairs and allows for quick access to the value associated with a key. Use it anytime you don't want numeric (or ordered) indices. qmap

Widgets

QWidgets are used for "standard" GUI components like as buttons, checkboxes, drop down menus, and so on. Because widgets are inherited from QObjects, we also have signals/slots and a parent-child relationship. It is best to utilize them for standard user interface components and customize them with a subset of CSS known as QSS and so-called stylesheets. There is, however, an option of drawing them yourself using the paintEvent() method, however this may be difficult.

Description Screenshot
Message Box - The QMessageBox class provides a modal dialog for informing the user or asking for and receiving an answer from the user. A message box displays a primary message to notify the user to an issue, an informative explanation to better clarify the message, or a query to the user. Furthermore, the message box can display an icon as well as ordinary buttons for receiving user answers.

Check out the Python implementation as well.
message_box
Custom Tooltip - When you hover your cursor over a widget, a tooltip will appear. Aside from conventional text, the tooltip may be styled with a subset of HTML.

Check out the Python implementation as well.
custom_tooltip
QWidget Custom Painting - To draw an arrow in the background, the method paintEvent() is overwritten. The majority of the drawing tasks required by GUI programs are handled by very efficient algorithms in QPainter. It can draw anything from fundamental graphical primitives like point, line, rectangle, ellipse, and polygon to more complex forms like vector routes.

Check out the Python implementation as well.
qwidget_custom_painting
Status Bar - The QStatusBar class implements a horizontal bar for displaying status information. We use a timer to regulate how long it takes the bar to reach 100%. We use three buttons to control the bar: start, stop, and reset.

Check out the Python implementation as well.
status_bar
Switch - The QStatusBar class implements a horizontal bar for displaying status information. We use a timer to regulate how long it takes the bar to reach 100%. We use three buttons to control the bar: start, stop, and reset.

Check out the Python implementation as well.
switch
Double range slider - The QStatusBar class implements a horizontal bar for displaying status information. We use a timer to regulate how long it takes the bar to reach 100%. We use three buttons to control the bar: start, stop, and reset.

Check out the Python implementation as well.
double_range_slider

MVC

What is Model-View-Controler?

It is a common method of separating concerns about the presentation and modification of dynamic content in graphical applications:

  • Model: It is concerned with connecting us to the data source. The data may already be in memory, or it may be requested from a database or read from a file. After receiving the necessary information, it organizes it into cells with potentially numerous rows and columns. It chooses what should and should not be displayed. Finally, the model provides an API for accessing, modifying, inserting, and removing cells. It determines what data interactions are permitted and how they are carried out.
  • View: It receives the model's data. The data already has a suitable structure, and the view is aware of the cells, rows, and columns that model has prepared. It is simply concerned with how those elements will be displayed. It selects the appropriate font, colors, spacing between elements, slider bars, and so forth.
  • Controller: The controller allows the user to interact with the data displayed in the view. The standard method is to collect user events such as keystrokes and mouse clicks and then call the relevant function from the model API.

How to implement it using Qt framework?

  1. QStandardItemModel is a simple implementation that is not suitable for large or complex models. It is designed for simplicity of use rather than high performance. It is distinguished by a shallow learning curve.

  2. The separation of real data storage and organization (which must occur in the model and the related proxy models) and presentation is an obvious benefit of QAbstractItemModel abstraction. Allows for complete customisation. It requires a thorough understanding of its inner workings.

Description Screenshot
String List Model - The QStringListModel class provides a simple model that stores a list of strings. It is suitable for use with a QListView or QComboBox.

Check out the Python implementation as well.
string_list_model
Tree Model - Simple implementation of a tree model. The items are stored using hierarchical relationships. It is suitable for use with a QTreeView.

Check out the Python implementation as well.
tree_model
Reorderable Tree View - Extending tree model to allow reordering of items. Reordering is triggered trough drag and drop mechanis in QTreeView. Selected item is moved with all its children to the new position.

Check out the Python implementation as well.
reorderable_tree_view
Custom Item Delegate - Custom item delegate for qListView/qListView. The item delegate is in charge of painting the items in the view. It is important to note that it can paint the items in all sorts of ways depending on their current role. So, everytime a user clicks on an item, you may change the role from display to edit and render a whole different widget. The examples show how to position the text and style it, as well as how to paint custom shapes and render custom widgets instead of text.

Check out the Python implementation as well.
custom_delegate
Matrix View - Display an array of arrays in a form of a table. Allow the user to define the precision of the floating point numbers.

Check out the Python implementation as well.
custom_delegate
File Directory Tree View - Extending tree model to allow reordering of items. Reordering is triggered trough drag and drop mechanis in QTreeView. Selected item is moved with all its children to the new position.

Check out the Python implementation as well.
file_dir_treeview
Crypto Ranking - Extending tree model to allow reordering of items. Reordering is triggered trough drag and drop mechanis in QTreeView. Selected item is moved with all its children to the new position.

Check out the Python implementation as well.
crypto_ranking
Emoji Picker - Extending tree model to allow reordering of items. Reordering is triggered trough drag and drop mechanis in QTreeView. Selected item is moved with all its children to the new position.

Check out the Python implementation as well.
emoji_picker

Graphics

Two main classes allow us to implement custom graphics: QPainter and QGraphicsView.

QPainter is capable of allowing you to manipulate pixels on a widget. It is used when we overwrite a widget's paintEvent() method. It is capable of interacting with both QBrush and QPen. Fill is done using brushes, while outlines are done with pens. A brush can be styled, colored, gradiented, or textured.

With the painter you have an option to draw a:

  • A Point;
  • A Line;
  • A Rectangle;
  • An Ellipse;
  • A Polygon.

The graphics scene framework allows you to arrange your geometry in a tree of QGraphicsItems and easily manipulate its components. Whatever you do, it's always QPainter who does the drawing. It is just abstracted away. Because QGraphicsItem is not derived from QObject, you don't have the signals/slots and so on, however you may use QGraphicsObject if you require them. The standard graphics item is more lightweight and includes certain additional features not provided by the widgets API. Similar to how there are standard widgets, there are a few basic graphics elements such as lines, rectangles, and so on. For everything unique, you must implement your own painting using QPainter, exactly like with widgets.

If your geometry is simple and does not require interactive and hierarchical features, you should use QPainter directly. Use QGraphicsView for anything complex and interactive.

Description Screenshot
Movable Image - We'll make a scene, and the scene will be shown with the elements we'll be adding. The QGraphicsView object is a widget created in designer that is used to display the contents of a QGraphicsScene. A moveable object may be readily spawned on a graphics scene. Because the scene retains track of its items, deletion is not an issue. You can change the item's appearance by using the paint event.

Check out the Python implementation as well.
movable_image
Image Cropper - QWidget has been subclassed in order to receive image drops and show them with an elipsoidal crop. When the widget's width and height are equal, the crop has a circular form.

Check out the Python implementation as well.
image_cropper
Transformations - The scale() function may scale the coordinate system by a specified offset, the rotate() function can rotate it clockwise, and the translate() function can translate it (i.e. add a given offset to the points). It is important to note that any transformation is a matrix multiplication. As a result, the order in the code should be inverted to the order in which the transformations should be applied.

Check out the Python implementation as well.
transformations
Moving balls - QGraphicView is a camera in Qt's universe, while QGraphicScene is a movie scene. In the actual world, the camera has one coordinate system and the scene has another; they do not match, but there is a transformation that connects them. When actors move in the film, their size on the scene may change while their real size stays constant. In the example, we use coloured balls to demonstrate how to control the position of an item on the scene.

Check out the Python implementation as well.
moving_balls

Files

QFile is an I/O device that allows you to read and write text and binary files and resources. A QFile can be used alone or, more easily, in conjunction with a QTextStream or QDataStream.

Description Screenshot
File Info - Display informations about files. Get list of files in a given directory and all its subdirectories. Use QFileInfo to get the file's name, size, and other data. Unfortunately, QFileInfo does not use many static methods, and you must create an object to access most of its features. We generate a large number of temporary objects that are destroyed immediately after usage.

Check out the Python implementation as well.
file_info
File Operations - Manipulate files, by copying, moving, or deleting them. Create a temporary directory, and fill it with text files. If any error occurs, display it in on the console.

Check out the Python implementation as well.
file_operations
Storage Info - Display informations about storage, like free space, total space, and used space. Show mounted volumes, and their names.

Check out the Python implementation as well.
storage_info
JSON Serialization - Serialize an object of a custom class to a JSON file. Deserialize a JSON file to an object of a custom class. Check if the objects are the same.

Check out the Python implementation as well.
json_serialization

Network

Concurrent Computing

Description Screenshot
Spawn Thread - Spawn a thread and run a function in it. Use internal Qt framework for managing threads.

Check out the Python implementation as well.
spawn_thread
Gui Thread - Ensure the GUI's responsiveness while the threads perform their tasks. When worker threads finish their work, the view is updated to show the results of their work. When the worker thread completes its task, QFutureWatcher emits the finished() signal. Regrettably, there is currently no support for clearing the watcher. One solution is to spawn the watchers along with the threads on the fly.

Check out the Python implementation as well.
gui_thread
Spawn Process - The QProcess allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Spawn a single process and wait for it to finish.

Check out the Python implementation as well.
CMD Interface - A simple command line interface that allows you to execute commands as if they were typed in the console.

Check out the Python implementation as well.
cmd_interface

Plots

Qt applications may be used to display simple static plots as well as build visually appealing, interactive dashboards. Aside from the native QtCharts library, Qt offers also support for the widely used Matplotlib. Any modern plotting library may, however, be used (with little effort).

Description Screenshot
Simple plot - Embed Matplotlib canvas into a Qt widget. Matplotlib provides several options for constructing useful, personalized, and beautiful plots to show data in the simplest and most effective way possible. All of the standard plotting options are accessible. A tool bar with dynamic functionality is also included.

Check out the Python implementation as well.
plot
Lasso selection - The lasso tool is used to select and deselect points on a graph.

Check out the Python implementation as well.
lasso_scatter
Histogram filtering - To select or deselect bins on the histogram, move one of the slider handles.

Check out the Python implementation as well.
histogram

Other

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

qt-widgets's People

Contributors

djeada avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

qt-widgets's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.