本文介绍了我如何在另一个线程Qt中显示MessageBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
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
TestClass.h
class TestClass: public QObject
{
Q_OBJECT
public slots:
void something()
{
TestThread *thread = new TestThread;
thread -> start();
}
};
TestThread.h
TestThread.h
class TestThread: public QThread
{
Q_OBJECT
protected:
void run()
{
sleep(1000);
QMessageBox Msgbox;
Msgbox.setText("Hello!");
Msgbox.exec();
}
};
如果我这样做,我会看到错误
If i'm doing this, i see error
我做错了什么?请帮我.我知道我不能在另一个线程中更改gui,但是我不知道在qt中的构造.
What am I doing wrong? Please help me. I know that I cant change gui in another thread, but i dont know constuctions in qt for this.
推荐答案
您正试图在非GUI线程中显示小部件.
You are trying to show widget in non-gui thread.
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();
}
};
这篇关于我如何在另一个线程Qt中显示MessageBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!