QT(42)-QT线程-线程调用槽函数

如果用主程序调用槽函数可能会造成阻塞,特别是槽函数运行需时比较长的情况下。这时用线程来运行槽函数比较合适。

1.主线程:
QT(42)-QT线程-线程调用槽函数_第1张图片

QT(42)-QT线程-线程调用槽函数_第2张图片不要指定父对象

1.创建一个槽函数的类 SlotObject
2. 主函数直接调用它
3.线程里调用它

 


1.创建一个槽函数的类 SlotObject

#ifndef SLOTOBJECT_H
#define SLOTOBJECT_H


#include 
class SlotObject:public QObject
{
   Q_OBJECT
  public:
      explicit  SlotObject(QObject *parent=0);
  signals:
   void sigNum(int num);
  public slots:
   void startCount();
};

#endif

SlotObject.cpp
 

//1.没有线程的版本

#include "SlotObject.h"

SlotObject::SlotObject(QObject *parent):
           QObject(parent)
{
   int i=0;
   for(i=1;i<=5;i++)
   {
     emit sigNum(i);
     sleep(1);
    }

} 


2. 主函数直接调用它
mainwindow.cpp 点击按钮后执行槽函数。

#include "ui_MainWindow.h"
#include 

MainWindow::MainWindow(QWidget *parent):
            QWidget(parent),
            ui(new Ui:: MainWindow)
{
    ui->setupUi(this);
    slotObj= new SlotObject(this);                        //this
    QObject::connect(slotObj,SIGNAL(sigNum(int)),
                     this,SLOT(onSigNum(int)));   

}

MainWindow::~MainWindow()
{
     delete ui;
}
//3.响应
MainWindow::onSigNum(int n)
{
   ui->te_show->append(QString::number(n));
}
//1.按下按钮时 
MainWindow::on_btn_start_clicked()
{
  //2.slotObj发送信号
  slotObj->startCount();                //阻塞在这
}

mainwindow.h

#ifndef SLOTOBJECT_H
#define SLOTOBJECT_H


#include 
class MainWindow:public QWidget
{
   Q_OBJECT
  public:
      explicit  MainWindow(QWidget *parent=0);
      ~ MainWindow();
  private slots:
   void onSigNum(int num);
   void on_btn_start_clicked();
  
 private:
   Ui::MainWindow *ui;
   SlotObject *slotObj;
};

#endif

3.线程执行这个槽函数
mainwindow.cpp

#include "ui_MainWindow.h"
#include 

MainWindow::MainWindow(QWidget *parent):
            QWidget(parent),
            ui(new Ui:: MainWindow)
{
  ui->setupUi(this);
  slotObj= new SlotObject();                  //1.创建对象 不能指定父对象
  QThread *thread = new QThread(this);        //2.创建QThread
  slotObj->moveToThread(thread);              //3.对象移到线程中去
  QObject::connect(slotObj,SIGNAL(sigNum(int)),
                   this,SLOT(onSigNum(int)));
  QObject::connect(ui->btn_start,SIGNAL(clicked()),
                   slotObj,SLOT(startCount()));

  thread->start();                            //4.启动线程

}

MainWindow::~MainWindow()
{
  delete ui;
  delete slotObj;
}


MainWindow::onSigNum(int n)
{
   ui->te_show->append(QString::number(n));
}


 

你可能感兴趣的:(qt,qt,开发语言)