这是我的代码:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
testApp w;
w.show();
TestClass *test = new TestClass;
QObject::connect(w.ui.pushButton, SIGNAL(clicked()), test, SLOT(something()));
return a.exec();
}
TestClass.h
class TestClass: public QObject
{
Q_OBJECT
public slots:
void something()
{
TestThread *thread = new TestThread;
thread -> start();
}
};
TestThread.h
class TestThread: public QThread
{
Q_OBJECT
protected:
void run()
{
sleep(1000);
QMessageBox Msgbox;
Msgbox.setText("Hello!");
Msgbox.exec();
}
};
如果我这样做,我看到错误
部件必须在GUI线程
中创建
我做错了什么?请帮帮我。我知道我不能改变gui在另一个线程,但我不知道在qt的结构为这个。
你做错了什么?
您正在尝试在非gui线程中显示小部件。
如何修复?
class TestClass: public QObject
{
Q_OBJECT
public slots:
void something()
{
TestThread *thread = new TestThread();
// Use Qt::BlockingQueuedConnection !!!
connect( thread, SIGNAL( showMB() ), this, SLOT( showMessageBox() ), Qt::BlockingQueuedConnection ) ;
thread->start();
}
void showMessageBox()
{
QMessageBox Msgbox;
Msgbox.setText("Hello!");
Msgbox.exec();
}
};
class TestThread: public QThread
{
Q_OBJECT
signals:
void showMB();
protected:
void run()
{
sleep(1);
emit showMB();
}
};