zoukankan      html  css  js  c++  java
  • 1、QThreadPool线程池的使用,线程和Widget通过QMetaObject::invokeMethod交互。

    自定义一个QThreadPool,N个线程QRunnable,线程和Widget通过QMetaObject::invokeMethod交互。

    QRunnable非继承自QObject,所以不可以用信号和槽的方式和Widget主界面交互,为了和Widget主界面交互,可以用QMetaObject::invokeMethod进行交互。

    1、创建一个Widget工程,并在Widget类下定义一个QThreadPool的私有变量MyThreadPool;

    2、在Widget的构造函数中设置MyThreadPool的属性,如:setMaxThreadCount(1)等等。

    3、新建一个私有槽函数 void showinfo(QString str);

    4、在Widget.cpp实现该函数,将str信息显示到界面的QLineEdit编辑框。

    5、在Widget的ui界面添加一个按钮,用于MyThreadPool创建一个任务,添加一个QLineEdit编辑框,用于显示str。

    6、为了和Widget交互,需要对QRunnable进行自定义封装,在构造函数中将Widget指针传递进去。

    代码如下:

    Widget.h

    #ifndef WIDGET_H
    #define WIDGET_H

    #include <math.h>
    #include <QWidget>
    #include <QLineEdit>
    #include <QThreadPool>
    //////////////////////////////////////////////////////
    namespace Ui {
    class Widget;
    }
    class Widget : public QWidget {
    Q_OBJECT
    public:
    Widget(QWidget *parent = 0);
    ~Widget();
    private slots:
    void on_emit_Btn_clicked();
    void Update_Result(QString);

    private:
    Ui::Widget *ui;
    QThreadPool MyThreadPool;
    };

    Widget.cpp

    #include "widget.h"
    #include "ui_widget.h"
    #include "qmyrunnable.h"
    Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
    {
    ui->setupUi(this);
    MyThreadPool.setMaxThreadCount(1);
    MyThreadPool.setParent(this);
    }
    Widget::~Widget()
    {
    MyThreadPool.waitForDone();
    delete ui;
    }

    void Widget::Update_Result(QString str)
    {
    ui->lineEdit_1->setText(str);
    }
    void Widget::on_emit_Btn_clicked()
    {
      MyThreadPool.start(new QMyRunnable(this));
    }

    QMyRunnable.h

    #ifndef QMYRUNNABLE_H
    #define QMYRUNNABLE_H
    #include <QTest>
    #include <QRunnable>

    class QMyRunnable : public QRunnable
    {
    public:
    QMyRunnable(QObject* obj);

    protected:
    void run();
    private:
    QObject* obj;
    };

    QMyRunnable.cpp

    #include "qmyrunnable.h"
    #include "widget.h"
    QMyRunnable::QMyRunnable(QObject* obj) : obj(obj)
    {
    }
    void QMyRunnable::run()
    {
      QString str = QString("%1+%2=%3").arg(1).arg(1).arg(1+1);
      QMetaObject::invokeMethod(obj,"Update_Result",Q_ARG(QString,str));
    QTest::qWait(100);
    }

    main.cpp

    #include <QtGui/QApplication>
    #include "widget.h"

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
    }
  • 相关阅读:
    为什么要持续输出
    从Libra看区块链的机遇
    windows 通过choco 安装 .net core windowshosting
    java 正则表达式空格无法匹配
    docker jenkins 安装
    docker jenkins 前端node项目 自动化部署异常 env: ‘node’: No such file or directory
    jenkin docker node 自动化部署配置
    centos docker redis 安装
    Windows server 2012 出现大量无名已断开连接用户清楚办法
    spring boot 打包jar后访问classes文件夹的文件提示地址不存在
  • 原文地址:https://www.cnblogs.com/zhangnianyong/p/8931290.html
Copyright © 2011-2022 走看看