我的目标是打开一个对话框。当用户单击OK时,它将循环打开同一个对话框。这意味着打开对话框必须阻止下一个打开。我无法通过第二次循环迭代,并且由于某些我不理解的原因,运行时失败。
这里是完整的文件内容,可以直接导入到Qt Creator中,作为一个最小的可复制示例。主函数在main.cpp
中定义为:
#include <QApplication>
#include <QObject>
#include <cstdio>
#include "MyClass.h"
int main(int argc, char *argv[])
{
MyClass obj;
QApplication a(argc, argv);
obj.Init(&a);
obj.start();
return a.exec();
}
以下是MyClass类MyClass.cpp
的内容:
#include "MyClass.h"
MyClass::MyClass() { }
void MyClass::openDialog()
{
// Create and execute the dialog box
QMessageBox messageBox;
messageBox.setText("Dialog Box");
messageBox.exec();
// Signal that the dialog box has closed
emit dialogClosed();
}
void MyClass::run() {
while (1){
printf("PRESS OK TO CONTINUE LOOPING...\n");
// Open dialog box within the GUI thread
QMetaObject::invokeMethod(this, "openDialog", Qt::QueuedConnection);
// Wait for dialog to close
QEventLoop loop;
connect(this, &MyClass::dialogClosed, &loop, &QEventLoop::quit);
loop.exec();
printf("LOOP ENDED.\n");
}
}
int MyClass::Init(QCoreApplication * App)
{
}
下面是头文件MyClass.h
:
#include <QThread>
#include <QCoreApplication>
#include <QMessageBox>
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass : public QThread
{
Q_OBJECT
private:
void run();
signals:
void dialogClosed();
public:
MyClass();
int Init(QCoreApplication *App);
public slots:
void openDialog();
};
#endif // MYCLASS_H
最后是Qt项目文件MyClass.pro
:
QT += core network
QT += widgets
CONFIG += c++11
SOURCES += main.cpp MyClass.cpp
HEADERS += MyClass.h
运行时,仅成功打开第一个对话框,然后不打开任何对话框。我得到以下终端输出:
QThread: Destroyed while thread is still running
1条答案
按热度按时间k4ymrczo1#
你必须调用
QEventLoop::exit
来终止事件循环。因为这个函数接受一个整数参数,所以由于信号和槽的工作方式,您必须将一个信号与一个匹配的参数连接起来。否则,你可以像这样将信号连接到lambda函数: