0


【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"intmain(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

#ifndefWORKER_H#defineWORKER_H#include<QObject>#include<QThread>classWorker:publicQObject{
    Q_OBJECT
public:explicitWorker(QObject *parent =nullptr);

    Q_INVOKABLE voidworkRun();

signals:public slots:};#endif// WORKER_H

worker.cpp

#include"worker.h"#include<QDebug>Worker::Worker(QObject *parent):QObject(parent){}voidWorker::workRun(){int count =0, count_one =0;longlong 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.9import QtQuick.Window 2.2import QtQuick.Controls 2.2import Tool 1.0

Window {visible:truewidth:640height:480title: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.9import 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

#ifndefWORKER_H#defineWORKER_H#include<QObject>#include<QThread>classWorker:publicQObject{
    Q_OBJECT
public:explicitWorker(QObject *parent =nullptr);

    Q_INVOKABLE voidworkRun();
    Q_INVOKABLE voidinitThread();
    Q_INVOKABLE voidbtnClick();

    QThread *m_thread;
    Worker *m_worker;

signals:voidbtnClicked();public slots:};#endif// WORKER_H

worker.cpp

#include"worker.h"#include<QDebug>Worker::Worker(QObject *parent):QObject(parent){}voidWorker::workRun(){int count =0, count_one =0;longlong 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;}voidWorker::initThread(){
    m_worker =newWorker();
    m_thread =newQThread();

    m_worker->moveToThread(m_thread);connect(this,&Worker::btnClicked, m_worker,&Worker::workRun);

    m_thread->start();}voidWorker::btnClick(){
    emit btnClicked();}

main.qml

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

Window {visible:truewidth:640height:480title: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.9import 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 ="";}}}}

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

标签: qt c++ ui

本文转载自: https://blog.csdn.net/weixin_45054387/article/details/128858137
版权归原作者 南方有大雪 所有, 如有侵权,请联系我们删除。

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

还没有评论