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

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 = "";
            }
        }
    }
}

下面是引入多线程后的效果图,界面卡顿明显消失了:

但是还是有问题的存在,就是有的耗时操作再子线程中一直运行,一直在跑,但是界面就一直在切换,如果是需要获取在耗时操作后的结果显示在界面的话,这种方法显然是不行的,未完待续。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值