当前位置: 首页 > news >正文

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

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

相关文章:

  • kob后端1
  • Kotlin~工厂方法、抽象工厂模式
  • C++继承(下)
  • PKI证书签发系统(2.0web版)
  • Ubuntu20.4下安装TensorFlow2.x
  • 【项目部署】Python Django部署到阿里云
  • MySQL数据库索引并没有你想的那么难之第一节
  • 数据结构与算法-单链表
  • 记一次git误操作, 合并冲突别人新增文件显示成“自己新增“绿色文件
  • Dubbo----------------------------配置信息整合SpringBoot的三种方式
  • 基于视觉的车道线识别技术在智能车导航中的应用研究
  • bleu-mp 多进程bleu评估工具
  • webpack多进程打包
  • 索尼IMX316 标定_ToF模块相机校准
  • 【Proteus仿真】【51单片机】智能鱼缸系统设计
  • 瑞吉外卖2.0 Redis 项目优化 Spring Cache MySQL主从复制 sharding-JDBC Nginx
  • 2023-02-04 Elasticsearch 倒排索引的理解 Trie前缀树原理
  • 【DIY小记】VMWare设置主机连接到的Ubuntu虚拟机的网络端口
  • Spring Boot 集成Quartz
  • 【Java学习】JUC并发编程
  • 电加热油锅炉工作原理_电加热导油
  • 大型电蒸汽锅炉_工业电阻炉
  • 燃气蒸汽锅炉的分类_大连生物质蒸汽锅炉
  • 天津市维修锅炉_锅炉汽化处理方法
  • 蒸汽汽锅炉厂家_延安锅炉厂家
  • 山西热水锅炉厂家_酒店热水 锅炉
  • 蒸汽锅炉生产厂家_燃油蒸汽发生器
  • 燃煤锅炉烧热水_张家口 淘汰取缔燃煤锅炉
  • 生物质锅炉_炉
  • 锅炉天然气_天燃气热风炉