Qt interview questions collection

  1. What are the five commonly used modules in Qt?

The five commonly used modules in Qt include:

  • QtCore: Provides Qt's core functions, such as basic non-GUI classes, threads and event handling.

  • QtGui: Provides user interface (UI) classes such as widgets, buttons, labels, etc. In addition, it contains drawing and palette classes such as QPainter and QPalette.

  • QtWidgets: It is a subset of the QtGui module, providing a complete set of visual UI control libraries, such as buttons, text editors, tables, etc., for building cross-platform desktop applications.

  • QtNetwork: Provides network programming classes for creating TCP and UDP clients and servers, as well as handling sockets and HTTP requests.

  • QtSql: Provides a simple and easy-to-use database access API for connecting, querying and operating data in data sources in Qt.

  1. What are signals and mechanisms? How to use signals and achieve communication between objects?

Signals and slots are mechanisms used in the Qt framework for communication between objects. A signal is a special type of function used to notify an object that an event has occurred. It is a function that receives signals. When a signal is triggered, the function connected to it will be automatically called. This can achieve decoupling between objects and flexible event handling processes.

Using signals and mechanisms can implement asynchronous programming within or between objects, and can also help developers decouple the code of different components and modules, improving the maintainability and scalability of the system.

  1. How to create a custom signal?

You can declare custom signals in the QObject class using the keyword signals. For example:

class MyObject : public QObject
{
    
    
    Q_OBJECT

signals:
    void mySignal();
};

Here, we have declared the custom signal "mySignal" in the class. You can choose not to write any parameters, which means it is a simple notification signal.

To trigger a signal, use syntax like emit mySignal(). For example:

void MyClass::someFunction()
{
    
    
    // do something ...
    emit mySignal();
}
  1. In Qt, why is it not recommended to create UI controls and modify their property values?

In Qt, it is recommended to treat UI controls (such as buttons, labels, etc.) as view-controllers (View-Controller), and separate the business logic part to ensure low coupling of the application. Therefore, processing business logic and directly changing property values ​​​​in UI controls may lead to a series of problems such as difficult code maintenance, redundant duplicate code, and inconvenience in file structure optimization.

On the contrary, by separating the business logic, you can better manage and test the code and maintain the clarity of the code. Modify interface controls by connecting signals and slots.

  1. What is QPainter? What scenarios is it used for?

QPainter is Qt's drawing engine, used to draw various graphic elements and render text. It provides many commonly used functions, such as drawing rectangles, circles, etc. to draw basic graphics. It also includes the ability to set brush width, color and style, font, gradient, pattern, transparency, etc., allowing users to present complex effects using relatively simple steps.

QPainter is particularly useful in GUI applications. By using QPainter, you can implement custom rendering on windows or other widgets, and create your own icons, charts, and data visualization tools to enhance the user experience of your application.

  1. What types of timers are there in Qt? What's the difference between them?

There are two types of timers in Qt:

  • QTimer: is a general-purpose, event-based timer used to trigger the timeOut() signal after a specified time interval.

  • QBasicTimer: is an auxiliary class for higher-level timing operations. It allows the object to create an internal timer and handle timeout events using the timerEvent() function.

Both support count-by-count or repeat triggering methods, but QBasicTimer manages its internal timer itself, making it more suitable for timer operations that require fine-grained operation.

  1. What is the difference between QThread and QtConcurrent? Which way do you use to handle multithreading in your project?

QThread is a basic class in Qt, used to create new threads in applications. Using QThread, you can create a new thread and put specific tasks in this thread to execute, so that the main thread will not be blocked. However, it should be noted that there are sometimes some problems that are difficult to solve when using QThread directly, such as memory leaks and problems when handling signals across threads.

QtConcurrent is a high-level API that provides many functions to facilitate loading and managing threads. By using QtConcurrent, you can easily write parallel code and execute algorithms using map-reduce mode. It is easier to use and manage, but less flexible.

As for which way to handle multi-threading in your project, it depends on the specific situation. If you need more fine-grained control, such as controlling threads at the program level, assigning priorities to threads, and detaching subordinate threads, you should use QThread. If all you need is a simple background thread to execute IO-intensive code or a large number of simple calculations, you can use QtConcurrent.

  1. What classes and functions does Qt provide for formatting characters and strings? What's the difference between them?

Qt provides many classes and functions that can format characters and strings, including:

  • QString: It is the most commonly used string class in Qt, supporting Unicode and localized characters and formatting;

  • QTextStream: It can add data to the stream using the << operator, and automatically performs string conversion and buffering;

  • QLocale: Provides locale-related functions such as date and number formatting;

  • QVariant: is a general value class that can be converted between specific formats and types.

These classes and functions each have their own advantages when dealing with different scenarios. QString provides general string processing functions; QTextStream is particularly good at handling file I/O operations; QLocale is obviously suitable for string operations that require internationalization, etc. Choosing the right tool will increase the efficiency and accuracy of your application.

  1. Why does QObject prohibit copy constructors and copy assignment operators?

QObject instances are usually considered nodes of an object tree, that is, they are grouped together hierarchically to form a hierarchy. In this hierarchy, each QObject instance has a parent object (except the top-level QObject object), and when the parent object is deleted, all child objects are automatically deleted.

If you allow copy constructors for QObject instances, this can cause certain problems, such as:

  1. Multiple instances refer to the same object and there is no way to determine which object is the "correct" one.

  2. When copying a QObject instance, we cannot determine which tree the object is in, the object's parent pointer is incorrect.

  3. If a newly created object is not properly registered, it may cause errors and memory leaks when the object is destroyed.

Therefore, QObject disables copy constructors and copy assignment operators to ensure that programmers do not accidentally trigger the above problems and to better manage them during development.

If you need to copy a QObject object, you can use QObject's clone() function or other custom functions to implement deep cloning operations, and ensure that references and pointers of all sub-objects are processed.

  1. How to handle file and directory operations in Qt? What classes and functions are available in Qt for reading and writing files?

In Qt, you can use the QFile class to read and write files. For file directory operations, the QDir class is a useful class. You can use QDir to traverse directories, filter and sort files, get information about files/directories, create and move files, and more.

The following are some common Qt file and directory manipulation functions:

  • QFile::open() - opens a file and returns a file handle;

  • QFile::readAll() - reads the entire file and returns a QByteArray of its contents;

  • QFile::write() - writes data to an open file;

  • QDir::setCurrent() - Set all absolute path base records;

  • QDir::exists() - Check whether a directory or file exists;

  • QDir::mkpath() - Create new directories recursively.

  1. How to perform database operations in Qt? What classes and functions are available in Qt for connecting to a database, executing queries and updating data?

Qt provides the QtSql module for database operations in Qt applications. It supports a variety of mainstream database engines, such as SQLite, MySQL, PostgreSQL and Oracle. The following are some common QtSql classes and functions:

  • QSqlDatabase: used to connect to a specific database engine and return a database object;

  • QSqlQuery: used to execute SQL queries and provide access to result sets;

  • QSqlTableModel: Provides a model-view interface, using model data corresponding to the records of the database table;

  • QSqlRelationalTableModel: A subclass of QSqlTableModel that supports associations between multiple tables.

The general steps for using QtSql to perform database operations are as follows:

  1. Choose the database engine to use, such as SQLite, MySQL or PostgreSQL. If you're not sure which engine you should choose, here are the pros and cons of each.

  2. Create and open a database connection (QSqlDatabase).

  3. Execute SQL queries or manipulate data. This usually involves using a QSqlQuery object.

  4. Process query results.

  5. Close the database connection.

Note: When writing QtSql code, you need to consider security issues such as multi-threading issues and SQL injection attacks. You can use QSqlQuery functions such as prepare() and bindValue() to mitigate SQL injection attack problems. It is also recommended to perform database operations in a separate thread to maintain high performance and better thread safety.

  1. What is the difference between QML and Qt Widgets?

QML and Qt Widgets are both UI development frameworks supported by Qt, but they are very different:

  1. Writing language: Qt Widgets uses C++ to write UI interfaces, while QML is based on JavaScript, XML and basic HTML/CSS.

  2. Technology: Qt Widgets combine elements using QWidget and QML (derived from Qt Quick's QQuickItem). Qt Widgets use a fixed coordinate layout, while QML uses a shader-based engine that supports adaptability and dynamic arrangement.

  3. Visual style: Qt Widgets provides a set of platform-independent widget libraries that are similar to the platform's native visual style. QML features flexible themes, templates, and skins to create fully Personalized user interfaces suitable for custom brands.

  4. Performance: QML's rendering performance is better than traditional Qt Widgets, and the effect is remarkable when handling complex 2D and 3D rendering tasks.

Choosing which framework to use depends on your needs and specific situation. Qt Widgets is suitable for those who pay more attention to the position, size and other properties of the control, while QML is just the opposite; if you need to customize your own CSS or JS, or need to implement complex animation/2D/3D rendering, etc., it is recommended to use QML.

  1. How to handle events of user interface elements in Qt? Specifically, how do I handle a button's click event?

In Qt, you can handle events of UI elements through the signal and plug-in mechanisms. The main steps are as follows:

  1. Define signals for UI elements. For example, QPushButton's clicked() signal indicates that the button has been clicked.

  2. Wire slot functions for UI elements. A slot function is a function that is called when an event occurs.

  3. Write slot functions to respond to signals. For example, the slot function executed when clicked() occurs could be a simple calculation or initiate other operations.

Here is sample code for QPushButton handling click events:

Declare in the Header file:

public slots:
    void onBtnClicked();

Implemented in the implementation file:

void MyWidget::onBtnClicked()
{
   // 按钮已被单击
}

Set up the connection in the constructor:

QObject::connect(ui->myButton, SIGNAL(clicked()), this, SLOT(onBtnClicked()));

Here, ui->myButton is the QPushButton object defined in the .ui file, and SIGNAL(clicked()) indicates that the clicked() signal will be emitted when the button is clicked. If you use the new syntax, you need to use QObject::connect() instead of the old syntax above.

  1. How to create custom components using QML?

In QML, you can use Component to create custom components. A Component is a special type of object that can be instantiated and used as part of QML. To create a Component, you can use a separate file or define multiple components in the same file.

The following example code defines a component:

// MyButton.qml
import QtQuick 2.0

Rectangle {
    id: root
    width: 100; height: 50
    color: "red"
    radius: 10

    signal clicked()

    Text {
        anchors.centerIn: parent
        text: "Click me!"
    }

    MouseArea {
        anchors.fill: parent
        onClicked: root.clicked()
    }
}

Here, we define a custom component called MyButton. This component contains a red rounded rectangle, text and a MouseArea. MouseArea receives click events and emits a clicked() signal to indicate that the button has been clicked. Next, we need to instantiate this component and use it as part of QML.

You can instantiate the MyButton component by adding the following code to your main QML file:

// main.qml
import QtQuick 2.0

Rectangle {
    width: 360; height: 360
    color: "#333"

    MyButton {
        x: 130; y: 130
        onClicked: console.log("Button clicked!")
    }
}

Here, we instantiate a MyButton component in the main QML file and add it to the main interface. When MyButton is clicked, we will output a message to the console.

  1. How to draw graphics in Qt?

In Qt, you can draw using the QPainter class, which provides a set of drawing devices and elements such as colors, line widths, and various geometric shapes. Here is a simple example showing how to draw a square using QPainter:

void MyWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 设置画笔和背景颜色
    painter.setPen(Qt::white);
    painter.setBrush(Qt::gray);

    // 绘制正方形
    QRectF rectangle(10.0, 20.0, 80.0, 60.0);
    painter.drawRect(rectangle);
}

To draw other graphics, you need to set up different QPainter functions, such as drawLine(), drawEllipse(), drawText(), and so on. You can also use the QPainterPath class to create complex custom graphics paths.

Note: When Qt uses QPainter to draw, drawing problems and performance issues may occur. If you need to do a lot of drawing operations or work with complex graphics, consider using a more efficient drawing technology such as OpenGL or Qt Quick's QML Canvas.

  1. How to use signals and slots mechanism for inter-object communication in Qt?

In Qt, messages and slots are a powerful way to implement communication between objects. Every object of type QObject has a signals: and slots: sections. Among them, signals: contains the required signal definitions, and slots: contains the slot functions that respond to the signals.

Here is a simple example using signals and slots to demonstrate how to pass data between two objects:

  1. Create sender class:
class Sender : public QObject
{
    
    
    Q_OBJECT

public:
    // 定义一个 signal ,以 int 类型发送数据
    void sendNumber(int number)
    {
    
    
        emit numberSent(number);
    }

signals:
    // 声明一个发送 int 类型数据的 signal
    void numberSent(int number);
};
  1. Create receiver class:
class Receiver : public QObject
{
    
    
    Q_OBJECT

public slots:
    // 定义一个接收 int 类型数据的 slot
    void receiveNumber(int number)
    {
    
    
        qDebug() << "Received number:" << number;
    }
};
  1. Connect signals and slots:
// 创建实例(或使用现有实例)
Sender sender;
Receiver receiver;

// 连接 Sender 的 numberSent(int) 信号到 Receiver 的 receiveNumber(int) 槽
QObject::connect(&sender, &Sender::numberSent, &receiver,Receiver::receiveNumber);

// 发送数据
sender.sendNumber(42); // receiver 将会输出 "Received number: 42"

Here, the Sender class defines a signal (numberSent) that sends int type data and sends the value to the signal transmitter. The Receiver class defines a slot (receiveNumber) that receives int type data and prints the data in its slot function.

Finally, we connect the two objects. When the Sender class calls sendNumber() to send a number, the connect() function will connect it to the receiveNumber() slot of the Receiver class, thus realizing communication between objects.

  1. How to handle network requests in Qt?

In Qt, you can use the Qt Network module to handle network requests and send and receive data across various protocols. Here is a simple example showing how to use the Qt Network module to send an HTTP GET request:

#include <QCoreApplication>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <Network/QNetworkRequest>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个 QNetworkAccessManager 实例
    QNetworkAccessManager manager;

    // 实例化请求对象
    QNetworkRequest request;
    request.setUrl(QUrl("http://www.example.com"));

    // 发送 GET 请求
    QNetworkReply *reply = manager.get(request);

    // 声明处理数据完成的槽
    QObject::connect(reply, &QNetworkReply::finished, [&]() {
    
    
        // 处理返回的数据
        if (reply->error() == QNetworkReply::NoError) {
    
    
            QString data = QString(reply->readAll());
            qDebug() << data;
        }
        else {
    
    
            qDebug() << "Network error:" << reply->errorString();
        }

        // 释放资源
        reply->deleteLater();
        a.quit();
    });

    return a.exec();
}

NOTE: When handling network requests, put them in a separate thread to avoid blocking the main loop and possible performance issues. You can use Qt classes such as QThread to handle multi-threaded requests. 18. How to use database in Qt?

In Qt, you can use the QSqlDatabase class to connect to and operate on a database. The following is a simple example demonstrating how to use Qt to connect to a SQLite database:

#include <QCoreApplication>
#include <QtSql>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 在默认位置创建数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("myDb.db");

    // 打开数据库后进行操作
    if (db.open()) {
    
    
        QSqlQuery query;

        // 建立表格
        query.exec("CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT)");

        // 插入数据
        query.exec("INSERT INTO people VALUES(1, 'Tom')");
        query.exec("INSERT INTO people VALUES(2, 'Jerry')");

        // 查询
        query.exec("SELECT id, name FROM people");
        while (query.next()) {
    
    
            int id = query.value(0).toInt();
            QString name = query.value(1).toString();
            qDebug() << "ID:" << << " Name:" << name;
        }

        // 关闭连接
        db.close();
    }
    else {
    
    
        qDebug() << "Failed to open database:" << db.lastError().text();
    }

    return a.exec();
}

Note: When using the QSqlDatabase class, please ensure that the required drivers are installed (for example, SQLite requires the SQLite driver that comes with Qt). Also note that Database uses a lot of resources. Remember to close/delete the connection when you no longer need it to avoid memory leaks and performance issues.

  1. How to provide multi-language support in Qt?

In Qt, you can use the QTranslator class to implement multi-language support for your application. Here's a simple example of how to add this functionality to your application:

  1. Create translation files using Qt Linguist

First, you need to create a translation file (.ts) using the Qt Linguist tool. This file contains all text strings that need to be translated and their corresponding translations. You can use part of the Qt Creator editor to open and edit .ts files, or use the command line tools lupdate and linguist to generate and edit them.

  1. Load translation files

In your application code, you can use the QTranslator class to load .qm translation files (compiled from .ts files). For example, here's a simple example of translation support for English and Spanish:

#include <QCoreApplication>
#include <QTranslator>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 加载翻译文件
    QTranslator translator;
    if (translator.load("myapp_es.qm")) {
    
    
        a.installTranslator(&translator);
    }

    // 执行其他操作
    // ...

    return a.exec();
}

Here, we load the Spanish translation file named myapp_es.qm and install it into the application. Then, when the text strings are displayed, they are automatically translated into the corresponding Spanish text.

  1. Recompile and deploy

Finally, remember to recompile your application and deploy the .qm file to the correct location so that the application can find this file and use it for multi-language support. 20. How to perform file and directory operations in Qt?

In Qt, you can use classes such as QFile, QDir, and QFileInfo for file and directory operations. Here are some simple examples:

  1. Create files and write data
#include <QCoreApplication>
#include <QFile>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个名为 myFile.txt 的文本文件,并向其中写入数据
    QFile file("myFile.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
    
    
        QTextStream stream(&file);
        stream << "Hello world!";
        file.close();
    }

    return a.exec();
}

Here, we use the QFile class to create a file named myFile.txt and write the "Hello world!" text data to it. Finally, we close the file to ensure all data has been written.

  1. Read file data

#include
#include

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

// 打开文件,并读取其中的数据
QFile file("myFile.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    QTextStream stream(&file);
    QString data = stream.readAll();
    file.close();
    qDebug() << data; // 输出文件包含的数据
}

return a.exec();

}


这里,我们打开名为 myFile.txt 的文件,并使用 QTextStream 类从中读取所有数据。然后,我们将文件中包含的数据打印到控制台上以进行验证。

3. 删除文件

```cpp
#include <QCoreApplication>
#include <QFile>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 删除名为 myFile.txt 的文件
    QFile::remove("myFile.txt");

    return a.exec();
}

Here, we use the static remove() function of the QFile class to delete the file named myFile.txt. You can use the rename() function to rename a file and the exists() function to see if a file exists.

  1. Traverse directory
#include <QCoreApplication>
#include <QDir>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 遍历名为 myFolder 的目录,并列举其中所有子文件和子目录
    QDir dir("myFolder");
    for (const QFileInfo& info : dir.entryInfoList()) {
    
    
        if (info.isDir()) {
    
    
            qDebug() << "Directory:" << info.fileName();
        }
        else {
    
    
            qDebug() << "File:" << info.fileName();
        }
    }

    return a.exec();
}

Here, we use the QDir class to open a directory named myFolder and use the entryInfoList() function to list the files and subdirectories in the directory. We then check if each entry is a directory or file and print their names to the console to verify. 21. How to perform thread operations in Qt?

In Qt, you can use the QThread class and QRunnable interface to perform multi-threaded tasks. Here are some simple examples:

  1. Use QThread to perform tasks
#include <QCoreApplication>
#include <QThread>

class MyWorker : public QObject {
    
    
    Q_OBJECT

public slots:
    void doWork() {
    
    
        qDebug() << "Worker thread ID:" << QThread::currentThread();
        // 执行其他操作
        // ...
        emit workFinished();
    }

signals:
    void workFinished();
};

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个新线程
    QThread* thread = new QThread;

    // 创建工作对象,并将其移动到新线程中
    MyWorker* worker = new MyWorker;
    worker->moveToThread(thread);

    // 连接信号和槽以启动工作线程
    QObject::connect(thread, &QThread::started, worker, &MyWorker::doWork);
    QObject::connect(worker, &MyWorker::workFinished, thread, &QThread::quit);
    QObject::connect(worker, &MyWorker::workFinished, worker, &MyWorker::deleteLater);
    QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater);

    // 启动线程
    thread->start();

    return a.exec();
}

Here, we created a work class named MyWorker, which implements a slot function doWork() to perform work tasks. Then, we create a QThread instance and move MyWorker to the thread of this QThread instance.

Next, we connect the QThread::started signal to MyWorker::doWork to start the worker thread. When the work is completed, MyWorker emits the workFinished signal and connects it to QThread::quit to stop the worker thread. Finally, we delete the QThread instance and MyWorker instance on the QThread::finished signal.

  1. Use QRunnable to perform tasks
#include <QCoreApplication>
#include <QThread>
#include <QThreadPool>

class MyTask : public QRunnable {
    
    
public:
    void run() override {
    
    
        qDebug() << "Task thread ID:" << QThread::currentThread();
        // 执行其他操作
        // ...
    }
};

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个新任务并执行
    MyTask* task = new MyTask;
    QThreadPool::globalInstance()->start(task);

    return a.exec();
}

Here, we have created a task named MyTask, which implements the QRunnable interface. Then, we created the MyTask instance and submitted it to the global thread pool for asynchronous execution using the QThreadPool::globalInstance()->start() function.

Note: If you want to control the behavior of the thread pool, you can use other functions of the QThreadPool class. For example, the setMaxThreadCount() function can be used to set the maximum number of threads, the releaseThread() function can release idle thread resources, and so on. 22. How to perform network programming in Qt?

In Qt, you can use classes such as QTcpServer, QTcpSocket, QUdpSocket, and QSslSocket for network programming. Here are some simple examples:

  1. TCP server
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个 TCP 服务器
    QTcpServer server;

    // 绑定服务器到本机地址和端口
    if (server.listen(QHostAddress::LocalHost, 12345)) {
    
    
        qDebug() << "Listening for incoming connections on port 12345...";

        // 接受传入连接
        while (server.isListening()) {
    
    
            QTcpSocket* client = server.nextPendingConnection();
            qDebug() << "New client connected from:" << client->peerAddress() << ":" << client->peerPort();

            // 向客户端发送欢迎消息
            client->write("Welcome to my server!");
            client->flush();

            // 接收并显示来自客户端的消息
            QByteArray data = client->readAll();
            qDebug() << "Client message:" << data;
        }
    }

    return a.exec();
}

Here, we create a TCP server and bind it to the local machine address (127.0.0.1) and port 12345. We then use the nextPendingConnection() function to block waiting for an incoming connection and display the address and port of the connecting client. Send a welcome message to the client through the client->write() function, and receive and display messages from the client using the readAll() function. You can implement the client using the QTcpSocket class.

  1. UDP client
#include <QCoreApplication>
#include <QUdpSocket>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个 UDP 套接字
    QUdpSocket socket;

    // 向本地主机 12345 端口发送数据报
    QByteArray data = "Hello, world!";
    QHostAddress addr("127.0.0.1");
    quint16 port = 12345;
    socket.writeDatagram(data, addr, port);

    return a.exec();
}

Here, we create a QUdpSocket instance and use the writeDatagram() function to send a Hello, world! datagram to the local host (127.0.0.1) and port 12345. You can use the QUdpSocket class in another application to receive this packet or communicate with it in other ways.

  1. SSL client
#include <QCoreApplication>
#include <QSslSocket>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    // 创建一个 SSL 连接套接字
    QSslSocket socket;

    // 连接到 SSL 服务器
    socket.connectToHostEncrypted("mysslserver.com", 443);

    if (socket.waitForEncrypted()) {
    
    
        qDebug() << "SSL handshake successful.";

        // 发送和接收数据
        socket.write("GET / HTTP/1.0\r\n\r\n");
        socket.flush();

        while (socket.waitForReadyRead()) {
    
    
            qDebug() << socket.readAll();
        }
    }
    else {
    
    
        qDebug() << "SSL handshake failed:" << socket.errorString();
    }

    return a.exec();
}

Here, we create a QSslSocket instance and use the connectToHostEncrypted() function to connect to port 443 of the SSL server named mysslserver.com. If the SSL handshake is successful, data is sent and received using the write(), flush(), and readAll() functions. You can use QSslSocket to implement an SSL server. Note that in order to make the SSL handshake as smooth as possible, it is better to subclass your Qt application using the QApplication rather than the QCoreApplication class and provide context to support certificate verification. 23. How to perform database operations in Qt?

In Qt, you can use classes such as QSqlDatabase, QSqlQuery, and QSqlTableModel to perform database operations. Here are some simple examples:

  1. Connect to a SQLite database and execute queries
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");

    if (db.open()) {
    
    
        qDebug() <<Database connection established.";

        QSqlQuery query;
        query.exec("CREATE TABLE IF NOT EXISTS mytable ("
                   "  id INTEGER PRIMARY KEY,"
                   "  name TEXT NOT NULL,"
                   "  age INTEGER);");

        if (query.isActive()) {
    
    
            qDebug() << "Table created successfully.";
        }
        else {
    
    
            qDebug() << "Table creation failed:" << query.lastError().text();
        }

        // 插入数据记录
        query.prepare("INSERT INTO mytable (name, age) VALUES (?, ?)");
        query.bindValue(0, "John Doe");
        query.bindValue(1, 25);
        if (query.exec()) {
    
    
            qDebug() << "Record inserted successfully.";
        }
        else {
    
    
            qDebug() << "Record insertion failed:" << query.lastError().text();
        }

        // 执行查询
        if (query.exec("SELECT * FROM mytable")) {
    
    
            while (query.next()) {
    
    
                int id = query.value(0).toInt();
                QString name = query.value(1).toString();
                int age = query.value(2).toInt();
                qDebug() << "ID:" << id << "Name:" << name << "Age:" << age;
            }
        }
        else {
    
    
            qDebug() << "Query execution failed:" <<.lastError().text();
        }
    }
    else {
    
    
        qDebug() << "Database connection failed:" <<.lastError().text();
    }

    return a.exec();
}

Here, we add a SQLite database using the addDatabase() function and set the database file path using the setDatabaseName() function. We then open the database and execute a SQL query to create a data table named mytable. If the query is successful, we insert a new record into the data table.

Next, we execute another SQL query to read the rows in mytable and use the next() function to move forward through the result set. Finally, we extract three integer values ​​from each row and print its ID, name, and age.

  1. Directly operate the data table through QSqlTableModel
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlTableModel>
#include <QDebug>

int main(int argc, char *argv[])
    QCoreApplication a(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");

    if (db.open()) {
    
    
        qDebug() << "Database connection established.";

        // 创建模型并绑定到数据表
        QSqlTableModel model;
        model.setTable("mytable");

        // 添加新行
        model.insertRows(0, 1);
        model.setData(model.index(0, 1), "Jane Smith");
        model.setData(model.index(0, 2), 30);
        model.submitAll();

        // 显示所有行
        model.select();
        for (int row = 0; row < model.rowCount(); ++row) {
    
    
            int id = model.index(row, 0).data().toInt();
            QString name = model.index(row, 1).data().toString();
            int age = model.index(row, 2).data().toInt();
            qDebug() << "ID:" << id << "Name:" << name << "Age:" << age;
        }
    }
    else {
    
    
        qDebug() << "Database connection failed:" << db.lastError().text();
    }

    return a.exec();
}

Here, we add the SQLite database again using the addDatabase() function and then open it. Next, we create a QSqlTableModel instance, bind it to the mytable data table, and insert a new row of data records. We then use the select() function to query the entire data table and display the ID, name, and age for all rows.

With the above code, you can connect to the database, execute queries and operate data tables in Qt.

おすすめ

転載: blog.csdn.net/qq_25549309/article/details/131698460