【QT】C++和QML使用多线程优化界面切换卡顿的方法

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

qt提供了一种声明式语言qml可以使用一些可视组件以及这些组件之间的交互来描述用户界面而c++可以只负责后台逻辑的处理将界面和后台分离开来由qml来做UI界面c++负责后端处理对我个人来说这样的方式大大的方便了对界面和逻辑的修改和维护;

由于UI界面是工作在主线程中的大多数时候在后端处理一些耗时操作会导致界面卡顿甚至卡死的情况,这个时候就需要将一些耗时处理放在子线程中来进行操作减少主线程的阻塞;
在QT使用多线程的方法有多种这里使用其中一种方法moveToThread就是直接将当前的一个对象移到另外一个线程上该对象的数据接收等处理的操作都在该线程上实现不会阻塞到主线程中导致卡顿;
这里先来看一个例子使用qml构建两个界面这两个界面可以根据界面上的按钮切换每次点击按钮添加一个耗时操作(这里使用的是在c++成员函数添加for循环来代替耗时操作)所以每次点击按钮两个界面之间的切换会有5秒左右的延时就是界面之间卡顿现象具体代码如下
c++代码:
main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "worker.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    qmlRegisterType<Worker>("Tool", 1, 0, "Worker");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

worker.h

#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QThread>

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = nullptr);

    Q_INVOKABLE void workRun();

signals:

public slots:
};

#endif // WORKER_H

worker.cpp

#include "worker.h"
#include <QDebug>

Worker::Worker(QObject *parent) : QObject(parent)
{

}

void Worker::workRun()
{
    int count = 0, count_one = 0;
    long long product = 1;

    for(int i = 0; i < 99999; i++)
    {
        count = i;
        count_one = count + 1;

        product = count * count_one ;

        qDebug() << "i = " << i;
        qDebug() << __func__ << __LINE__ << "current product:" << product;
    }
}

qml代码
main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import Tool 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Worker {
        id:worker;
    }

    Rectangle {
        anchors.fill:parent;
        color: "lightblue";

        Text {
            id: ttt
            text: qsTr("text")
            font.pixelSize: 30;
            anchors.centerIn: parent;
        }

        Button {
            id:btn;
            text:"update";

            onClicked: {
                console.log("update data...");
                worker.workRun();
                pageChange.source = "qrc:/homePage.qml";
            }
        }

        Loader {
            id:pageChange;
            anchors.fill: parent;
            source: "";
        }
    }
}

homePage.qml

import QtQuick 2.9
import QtQuick.Controls 2.2

Item {
    anchors.fill: parent;

    Rectangle {
        anchors.fill: parent;
        color: "grey";

        Text {
            id: txt
            text: qsTr("welcome to homePage!!!");
            anchors.centerIn: parent;
            font.pixelSize: 40;
        }
        Button {
            id:closeBtn;
            text:"closeBtn";
            font.pixelSize:40;
            onClicked:{
                worker.workRun();
                pageChange.source = "";
            }
        }
    }
}

如以上代码所示添加的耗时操作阻塞在主线程中导致UI卡顿演示信息如下
在这里插入图片描述
每次切换之后都需要等一段时间才能切换在实际使用过程中这种卡顿是非常影响使用的这里试着用多线程的方法来修改将这个耗时操作放在子线程中去进行处理避免主线程阻塞;
下面是改过之后的代码使用信号和槽来连接主线程和子线程之间的通信主线程发送点击信号触发槽函数在子线程运行这样耗时操作就在子线程中处理界面不会再卡顿;
worker.h

#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QThread>

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = nullptr);

    Q_INVOKABLE void workRun();
    Q_INVOKABLE void initThread();
    Q_INVOKABLE void btnClick();

    QThread *m_thread;
    Worker *m_worker;

signals:
    void btnClicked();

public slots:
};

#endif // WORKER_H

worker.cpp

#include "worker.h"
#include <QDebug>

Worker::Worker(QObject *parent) : QObject(parent)
{

}

void Worker::workRun()
{
    int count = 0, count_one = 0;
    long long product = 1;

    qDebug() << "workRun thread id:" << QThread::currentThreadId();

    for(int i = 0; i < 99999; i++)
    {
        count = i;
        count_one = count + 1;

        product = count * count_one ;

        for(int j = 0; j < 10000; j++)
        {

        }
        qDebug() << "i = " << i;
        qDebug() << __func__ << __LINE__ << "current product:" << product;
    }
    qDebug() << __func__ << __LINE__ << "current product:" << product;
}


void Worker::initThread()
{
    m_worker = new Worker();
    m_thread = new QThread();

    m_worker->moveToThread(m_thread);

    connect(this, &Worker::btnClicked, m_worker, &Worker::workRun);

    m_thread->start();
}

void Worker::btnClick()
{
    emit btnClicked();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import Tool 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Worker {
        id:worker;
    }

    Component.onCompleted: {
        worker.initThread();
    }

    Rectangle {
        anchors.fill:parent;
        color: "lightblue";

        Text {
            id: ttt
            text: qsTr("text")
            font.pixelSize: 30;
            anchors.centerIn: parent;
        }

        Button {
            id:btn;
            text:"update";

            onClicked: {
                console.log("update data...");
                worker.btnClick();
                //worker.workRun();
                pageChange.source = "qrc:/homePage.qml";
            }
        }

        Loader {
            id:pageChange;
            anchors.fill: parent;
            source: "";
        }
    }
}

homePage.qml

import QtQuick 2.9
import QtQuick.Controls 2.2

Item {
    anchors.fill: parent;

    Rectangle {
        anchors.fill: parent;
        color: "grey";

        Text {
            id: txt
            text: qsTr("welcome to homePage!!!");
            anchors.centerIn: parent;
            font.pixelSize: 40;
        }
        Button {
            id:closeBtn;
            text:"closeBtn";
            font.pixelSize:40;
            onClicked:{
                worker.btnClick();//不直接操作workRun,触发信号由子线程中处理
                //worker.workRun();
                pageChange.source = "";
            }
        }
    }
}

下面是引入多线程后的效果图界面卡顿明显消失了
在这里插入图片描述
但是还是有问题的存在就是有的耗时操作再子线程中一直运行一直在跑但是界面就一直在切换如果是需要获取在耗时操作后的结果显示在界面的话这种方法显然是不行的未完待续。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: c++