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 objective of this repository is to compile a comprehensive collection of reusable Qt widgets suitable for integration into any application. This approach eliminates the need to develop common components from scratch for each new project, allowing developers to concentrate on customization and enhancement.

Requirements

For C++ Projects:

  • C++14
  • CMake 3.10+
  • Qt6

For Python Projects:

  • Python 3.10+
  • Dependencies specified in the project's requirements.txt file

Compilation Instructions

Using Qt Creator IDE

To initiate the project, open the relevant CMakeLists.txt file in Qt Creator.

Using Terminal

  1. Set the environment variable CMAKE_PREFIX_PATH to the Qt6 installation path.
  2. Open the terminal in the project directory and execute the following commands:

For Windows:

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

For Linux/macOS:

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

PyQt Projects

The recommended method for running PyQt projects is to use virtualenv:

  1. Create and activate a virtual environment:
$ virtualenv env
$ source env/bin/activate
  1. Install the required dependencies:
$ pip install -r requirements.txt
  1. Run the application:
$ python main.py

To convert .ui files to .py scripts, use the following Python snippet:

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 entire Qt ecosystem. It encompasses two crucial mechanisms:

  1. Slots and Signals:

    • Signals and slots are used for communication between objects.
    • A signal is emitted when a particular event occurs.
    • Slots are functions that are called in response to a signal.
    • This mechanism is central to Qt and allows for a flexible and reusable object-oriented code.
  2. Parent-Child Relationship:

    • The parent-child relationship ensures that child objects are automatically deleted when their parent is deleted.
    • This is crucial for managing the lifecycle of objects and preventing memory leaks.

When subclassing QObject, it is necessary to include the Q_OBJECT macro in the declaration to enable these mechanisms. Below is an example of how to subclass QObject:

class SubClass : public QObject {
  Q_OBJECT

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

signals:
  void someSignal();

public slots:
  void someSlot();
};

Examples and Demonstrations

Description Screenshot
Children Generator - Demonstrates the parent-child relationship in Qt. This generator can create and delete children dynamically. When the generator instance is destroyed, all of its children are also destroyed. children_generator
Custom Signal and Slots - A slot is a standard method that can be connected to a signal. Multiple slots can be connected to a single signal. A signal is a value that can be emitted by any function, and when emitted, the value is passed as a parameter to all associated slots.

Python Implementation: Custom Signal and Slots in Python
custom_signal_slots
Smart Pointers - A smart pointer is an abstract data type that has all the properties of a raw pointer along with automated garbage collection. Qt provided smart pointers before they were included in the C++ standard. They are used in some projects, but raw pointers are typically used for QObjects because they utilize a parent-child model for managing object lifecycles. smart_pointers
QVariant and QMetaType - The QVariant class acts as a union for the most commonly used Qt data types. Because C++ prohibits unions from containing types with non-default constructors or destructors, most useful Qt classes cannot be used in raw unions. The type is registered using the Q_DECLARE_METATYPE(Type) macro, enabling QMetaType to recognize the type. Q_DECLARE_METATYPE requires the class or struct to have a default constructor, copy constructor, and 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 they were created prior to the standardization of STL containers. Some features, like the contains() function, were first added in C++20, about 30 years later.

So the obvious question is whether you should use Qt's containers or STL. The ones from Qt are fully integrated into the Qt APIs, so compatibility is an important consideration. There is no clear winner in terms of efficiency and performance, and both are viable options. However, using the STL 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 maintains a list of values and allows for rapid index-based access as well as quick insertions and deletions. Despite being implemented as an array-list, it has very fast prepends and appends. QList is the ideal type to use for most purposes. This example shows how to initialize, display, and find and delete the list's elements.

A quick note 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 a 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 contiguous way in memory, whereas QList does not guarantee this. qlist_vs_qvector
QSet - QSet ensures the uniqueness of its 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 such as buttons, checkboxes, drop-down menus, and more. Since widgets inherit from QObjects, they also have signals/slots and a parent-child relationship. It is best to use them for standard user interface components and customize them with a subset of CSS known as QSS and stylesheets. There is also the option of drawing them yourself using the paintEvent() method, although this can be challenging.

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 of an issue, an informative explanation to clarify the message, or a query to the user. The message box can also display an icon and standard buttons for receiving user responses.

Check out the Python implementation as well.
message_box
Custom Tooltip - When you hover your cursor over a widget, a tooltip will appear. Besides conventional text, the tooltip can 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 paintEvent() method is overridden. Most drawing tasks required by GUI programs are handled by highly efficient algorithms in QPainter. It can draw anything from basic graphical primitives like points, lines, rectangles, ellipses, and polygons to more complex shapes like vector paths.

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

Check out the Python implementation as well.
status_bar
Switch - The QSwitch class is used to create switch buttons, providing a way to toggle between two states. This example shows how to create and customize switch buttons.

Check out the Python implementation as well.
switch
Double Range Slider - The QDoubleRangeSlider class implements a slider that allows for selecting a range between two values. This example shows how to create and customize double range sliders.

Check out the Python implementation as well.
double_range_slider

MVC

What is Model-View-Controller (MVC)?

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

  • Model: Responsible for connecting to the data source. The data may already be in memory, 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 determines what should and should not be displayed and provides an API for accessing, modifying, inserting, and removing cells. The model also decides what data interactions are permitted and how they are carried out.
  • View: Receives the model's data, which already has a suitable structure. The view is aware of the cells, rows, and columns that the model has prepared and is concerned with how those elements will be displayed. It handles the appropriate fonts, colors, spacing between elements, slider bars, and so forth.
  • Controller: Allows the user to interact with the data displayed in the view. It collects user events such as keystrokes and mouse clicks and then calls the relevant function from the model API.

How to implement it using the Qt framework?

  1. QStandardItemModel: A simple implementation that is not suitable for large or complex models. It is designed for ease of use rather than high performance and has a shallow learning curve.
  2. QAbstractItemModel: Provides the separation of real data storage and organization (which must occur in the model and the related proxy models) from the presentation. This allows for complete customization but 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 - Extends the tree model to allow reordering of items. Reordering is triggered through drag-and-drop mechanisms in QTreeView. The 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/QTableView. The item delegate is responsible for painting the items in the view. It can paint the items in various ways depending on their current role. For instance, when a user clicks on an item, you can change the role from display to edit and render a completely different widget. This example shows 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 - Displays an array of arrays in the form of a table. Allows the user to define the precision of the floating point numbers.

Check out the Python implementation as well.
matrix_view
File Directory Tree View - A tree model implementation for displaying file directories. It supports reordering of items through drag-and-drop mechanisms in QTreeView. The selected item is moved with all its children to the new position.

Check out the Python implementation as well.
file_dir_treeview
Crypto Ranking - A tree model for displaying cryptocurrency rankings. It allows for reordering of items through drag-and-drop mechanisms in QTreeView. The selected item is moved with all its children to the new position.

Check out the Python implementation as well.
crypto_ranking
Emoji Picker - A tree model for displaying emojis. It allows for reordering of items through drag-and-drop mechanisms in QTreeView. The 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 allows you to manipulate pixels on a widget. It is used when we overwrite a widget's paintEvent() method. It can interact with both QBrush and QPen. Filling is done using brushes, while outlines are created with pens. A brush can be styled, colored, gradiented, or textured.

With QPainter, you have the option to draw:

  • 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. Regardless of the complexity, QPainter handles the drawing, which is abstracted away. Since QGraphicsItem is not derived from QObject, it lacks signals/slots; however, you can use QGraphicsObject if you need those features. The standard graphics item is more lightweight and includes additional features not provided by the widgets API. Like standard widgets, there are basic graphics elements such as lines and rectangles. For unique elements, you must implement your own painting using QPainter, similar to custom widgets.

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

Description Screenshot
Movable Image - Create a scene and display it with elements added. The QGraphicsView object is a widget created in Designer to display the contents of a QGraphicsScene. A movable object can be easily spawned on a graphics scene. Since the scene keeps track of its items, deletion is not an issue. You can change the item's appearance using the paint event.

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

Check out the Python implementation as well.
image_cropper
Transformations - The scale() function scales the coordinate system by a specified offset, the rotate() function rotates it clockwise, and the translate() function translates it (i.e., adds a given offset to the points). Note that any transformation is a matrix multiplication, so the order in the code should be inverted relative to the order in which the transformations should be applied.

Check out the Python implementation as well.
transformations
Moving Balls - QGraphicView acts like a camera in Qt's universe, while QGraphicScene is a movie scene. The camera and the scene have separate coordinate systems, connected by a transformation. As actors move in the film, their size on the scene may change while their real size remains constant. This example uses colored balls to demonstrate how to control the position of an item on the scene.

Check out the Python implementation as well.
moving_balls

Files

File handling is a fundamental aspect of many applications, and Qt provides a comprehensive set of classes to facilitate reading from and writing to files. The primary class for file handling in Qt is QFile, which is an I/O device that allows you to manipulate text and binary files and resources.

QFile can operate in several modes, including read-only, write-only, and read-write. It supports both synchronous and asynchronous operations, providing flexibility depending on the needs of your application. For easier and more efficient file manipulation, QFile is often used in conjunction with other classes such as QTextStream, QDataStream, and QFileInfo.

  • QFile: The basic class for file handling, allowing opening, closing, reading, and writing files. It can work with text or binary data.
  • QTextStream: Used with QFile to handle text file operations more conveniently. It provides functions for reading and writing text, including support for different encodings.
  • QDataStream: Facilitates reading and writing binary data to and from a QFile. It ensures that the data is read and written in a consistent format across different platforms.
  • QFileInfo: Provides information about files and directories. It can be used to retrieve file names, sizes, last modified times, and other attributes.
Description Screenshot
File Info - Displays information about files. Get a 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. This results in generating a large number of temporary objects that are destroyed immediately after usage.

Check out the Python implementation as well.
file_info
File Operations - Manipulates files by copying, moving, or deleting them. Creates a temporary directory and fills it with text files. If any error occurs, it is displayed on the console.

Check out the Python implementation as well.
file_operations
Storage Info - Displays information about storage, such as free space, total space, and used space. Shows mounted volumes and their names.

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

Check out the Python implementation as well.
json_serialization

Network

Qt provides powerful classes for network programming, allowing you to create both client and server applications. The main classes for handling network operations in Qt are QNetworkAccessManager, QTcpSocket, and QUdpSocket.

  • QNetworkAccessManager: Manages the network operations, such as sending network requests and receiving replies. It supports HTTP and FTP protocols and can be used to download files or communicate with REST APIs.
  • QTcpSocket: Allows you to create TCP clients that can connect to TCP servers, send and receive data.
  • QUdpSocket: Provides an interface for UDP socket communication, enabling you to send and receive UDP datagrams.

These classes provide a robust framework for implementing various network functionalities, from simple data transfers to complex network protocols.

Concurrent Computing

Qt's concurrent programming module provides classes to help you manage threads and asynchronous operations easily. It includes classes like QThread, QtConcurrent, and QProcess, which allow for spawning threads, running tasks concurrently, and handling external processes.

  • QThread: Represents a thread and allows you to manage its execution.
  • QtConcurrent: Offers high-level APIs for running functions in parallel, making it simpler to utilize multiple cores.
  • QProcess: Enables the execution of external programs and facilitates interaction with their input/output streams.
Description Screenshot
Spawn Thread - Spawns a thread and runs a function in it using the internal Qt framework for managing threads.

Check out the Python implementation as well.
spawn_thread
Gui Thread - Ensures the GUI's responsiveness while the threads perform their tasks. When worker threads finish their work, the view is updated to show the results. QFutureWatcher emits the finished() signal when the worker thread completes its task. There is no direct support for clearing the watcher, so a common solution is to spawn the watchers along with the threads dynamically.

Check out the Python implementation as well.
gui_thread
Spawn Process - QProcess allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This example spawns a single process and waits 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 can display simple static plots as well as build visually appealing, interactive dashboards. In addition to the native QtCharts library, Qt also supports the widely used Matplotlib. However, any modern plotting library can be integrated with minimal effort.

Description Screenshot
Simple plot - Embeds a Matplotlib canvas into a Qt widget. Matplotlib offers several options for constructing useful, personalized, and beautiful plots to display data in the simplest and most effective way possible. All standard plotting options are accessible, and a toolbar with dynamic functionality is 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 - Allows selection or deselection of bins on the histogram by moving one of the slider handles.

Check out the Python implementation as well.
histogram

How to Contribute

We encourage contributions that enhance the repository's value. To contribute:

  1. Fork the repository.
  2. Create your feature branch (git checkout -b feature/AmazingFeature).
  3. Commit your changes (git commit -m 'Add some AmazingFeature').
  4. Push to the branch (git push origin feature/AmazingFeature).
  5. Open a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Star History

Star History Chart

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  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.