如何在多线程程序中连接信号和插槽?

时间:2012-12-22 04:57:04

标签: multithreading qt

mainwindow.cpp:

#include "ui_mainwindow.h"
#include <QtCore>

/* ****** Thread part ****** */
myThread::myThread(QObject *parent)
    : QThread(parent)
{
}

void myThread::run()
{
    while(1){
        qDebug("thread one----------");
        emit threadSignal1();
        usleep(100000);
    }
    exec();
}

myThread2::myThread2(QObject *parent)
    : QThread(parent)
{
}

void myThread2::run()
{
    while(1){
        qDebug("thread two");
        emit threadSignal2();
        usleep(100000);
    }
    exec();
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    onethread = new myThread(this);
    onethread->start(QThread::NormalPriority);

    twothread = new myThread2(this);
    twothread->start(QThread::NormalPriority);

    connect(onethread, SIGNAL(onethread->threadSignal1()),
            this, SLOT(mySlot1()));
    connect(twothread, SIGNAL(threadSignal2()),
            this, SLOT(mySlot2()),Qt::QueuedConnection);
}

void MainWindow::mySlot1()
{
    ui->textEdit1->append("This is thread1");
}

void MainWindow::mySlot2()
{
    ui->textEdit1->append("This is thread2");
}

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

void MainWindow::on_pushButton_clicked()
{
    ui->textEdit1->append("textEdit1");
    ui->textEdit2->append("textEdit2");
}

mainwindow.h:

#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>

namespace Ui {
class MainWindow;
}

class myThread : public QThread
{
  Q_OBJECT

public:
    myThread(QObject *parent = 0);
    void run();

signals:
    void threadSignal1();
};

class myThread2 : public QThread
{
  Q_OBJECT

public:
    myThread2(QObject *parent = 0);
    void run();

signals:
    void threadSignal2();
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void mySlot1();
    void mySlot2();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    myThread *onethread;
    myThread2 *twothread;
};

#endif // MAINWINDOW_H

请检查以上代码。它可以正常提供qDebug输出,而textEdit1 / 2没有任何输出。它似乎是一个多线程信号/插槽连接问题。谁可以帮忙?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要将插槽定义为插槽:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void mySlot1();
    void mySlot2();
...

还有一些其他的事情。您不需要在每个线程中进行exec()调用。无论如何,它们将进入无限循环,永远不会达到这种说法。并且,exec()的目的是在线程中启动事件循环,以便它可以接收并处理事件,例如拥有自己的插槽。你只是在散发。

您确定此连接有效吗?

connect(onethread, SIGNAL(onethread->threadSignal1()),
        this, SLOT(mySlot1()));

应该是:

connect(onethread, SIGNAL(threadSignal1()),
        this, SLOT(mySlot1()));

我相信QueuedConnection会隐含在连接中,因为它们的目标是与发射器不同的线程中的所有者的插槽。