Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Introduction to C++ Qt Framework

Tech 1

Installation

Download the community version from:

Common Shortcuts

[Image placeholder]

Developing Qt with CLion

CLion Qt Development Guide

Signals and Slots

  • Signals and slots are one of Qt's proudest mechanisms. Mastering them helps design decoupled, elegant programs.
  • Signals and slots implement the observer pattern. When an event occurs (e.g., a button click), a signal is emitted. Any object interested in this signal can connect to it using the connect() function, specifying a slot (function) to handle the signal.
connect(sender, SIGNAL(signal), receiver, SLOT(slot), Qt::DirectConnection);

Connection Types

Parameter Description
Qt::AutoConnection Default. Uses Qt::DirectConnection if sender and receiver are in the same thread; otherwise, Qt::QueuedConnection.
Qt::DirectConnection Slot is called immediately in the sender's thread. Risky in multithreading.
Qt::QueuedConnection Slot is called when the receiver's event loop processes it. Safe for multithreading.
Qt::BlockingQueuedConnection Similar to Qt::QueuedConnection, but the sender blocks untill the slot completes. Deadlocks if sender and receiver are in the same thread.
Qt::UniqueConnection Prevents duplicate connections when combined with other flags.

Meta-Object System

QObject *obj = new QPushButton;
obj->metaObject()->className(); // Returns "QPushButton"

QTimer *timer = new QTimer;
timer->inherits("QTimer"); // true
timer->inherits("QObject"); // true
timer->inherits("QAbstractButton"); // false

Property System

Defining Properties

Q_PROPERTY(type name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)

Dynamic Properties

bool setProperty(const char *name, const QVariant &value);
QObject obj;
obj.setProperty("flat", true);

Class Metadata

Q_CLASSINFO("AUTHOR", "John Doe")
Q_CLASSINFO("VERSION", "1.0")

// Retrieve metadata
this->metaObject()->classInfo(0).name();
this->metaObject()->classInfo(0).value();

Qt Global Definitions

forever {
    // Infinite loop
}

Qt Container Classes

Example Usage

QList<QString> list;
list << "one" << "two" << "three";
QString str = list.at(0); // "one"

QStack<int> stack;
stack.push(1);
stack.push(2);
qDebug() << stack.pop(); // 2

QMap<QString, int> map;
map["key"] = 42;
qDebug() << map.value("key"); // 42

Iterators

Container Read-Only Iterator Read-Write Iterator
QList, QQueue QList::const_iterator QList::iterator
QVector, QStack QVector::const_iterator QVector::iterator
QMap, QMultiMap QMap::const_iterator QMap::iterator

Core Modules

Module Description
Qt Core Non-GUI foundational classes.
Qt GUI GUI foundational classes.
Qt Network Simplified networking classes.
Qt SQL Database operations.
Qt Widgets UI elements for classic interfaces.

Additional Modules

Module Description
Qt Bluetooth Bluetooth hardware access.
Qt WebEngine Embed web content in apps.
Qt Charts 2D charting components.

Tools

Tool Description
Qt Designer UI design tool.
Qt Assistant Documentation viewer.

QSpinBox Example

void Widget::setTotal() {
    int quantity = ui->spinBoxQuantity->value();
    float price = ui->spinBoxPrice->value();
    ui->spinBoxTotal->setValue(quantity * price);
}

QFile Operations

Reading a File

QFile file("path/to/file.txt");
if (file.open(QIODevice::ReadOnly)) {
    QByteArray content = file.readAll();
    file.close();
}

Recursive Directory Traversal

QStringList getFiles(const QString &path) {
    QStringList files;
    QDir dir(path);
    for (const QFileInfo &info : dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot)) {
        if (info.isDir()) {
            files.append(getFiles(info.absoluteFilePath()));
        } else {
            files.append(info.absoluteFilePath());
        }
    }
    return files;
}

QMessageBox

QMessageBox::information(this, "Info", "Operation completed.");
QMessageBox::warning(this, "Warning", "File not saved.");

Model/View Architecture

QFileSystemModel

QFileSystemModel *model = new QFileSystemModel;
model->setRootPath(QDir::currentPath());
ui->treeView->setModel(model);

QStandardItemModel

QStandardItemModel *model = new QStandardItemModel;
model->setHorizontalHeaderLabels({"Name", "Value"});
QStandardItem *item = new QStandardItem("Data");
model->appendRow(item);
ui->tableView->setModel(model);

Custom Dialogs

Create a new QDialog subclass for custom dialogs.

MDI Applications

QMdiArea *mdiArea = new QMdiArea;
QMdiSubWindow *subWindow = mdiArea->addSubWindow(new QWidget);
subWindow->setWindowTitle("Document");
Tags: C++qtgui

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.