这是我的代码:
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中的构造。
答案 0 :(得分:7)
你做错了什么?
您正尝试在非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();
}
};