0

主窗口.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");
}

主窗口.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

请检查上面的代码。qDebugtextEdit1/2 没有任何输出时,它可以正常输出。这似乎是一个多线程信号/插槽连接问题。谁能帮忙?谢谢!

4

1 回答 1

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连接是隐含的,因为它们的目标是在与发射器不同的线程中的所有者上的插槽。

于 2012-12-22T05:44:27.127 回答