我有一个QDialog和QStateMachine。当所有应用程序关闭时,此循环终止但我想在Qdialog关闭时终止循环。我怎么能这样做?
QStateMachine sm;
QState s1(&sm), s2(&sm);
sm.setInitialState(&s1);
QEventTransition transition(dialog, QEvent::Close);
s2.addTransition(&transition);
QEventLoop loop;
QObject::connect(&s2, &QState::entered, &loop, &QEventLoop::quit);
sm.start();
dialog->show();
loop.exec();
答案 0 :(得分:2)
为此使用QFinalState
类。在docs示例显示使用QPushButton
并退出。您只需将其与finished()
信号连接即可。
<强> UPD 强>
一些用法示例:
MainWinow.h
class MainWindow : public QMainWindow, private Ui::MainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
private:
QDialog *dialog;
private slots:
void on_pushButton_clicked();
};
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setupUi(this);
dialog = new QDialog;
}
void MainWindow::on_pushButton_clicked()
{
// Open dialog after push button was clicked
if (!dialog)
dialog = new QDialog;
QEventLoop loop;
QStateMachine machine;
QState *s1 = new QState();
QFinalState *s2 = new QFinalState();
s1->addTransition(dialog, SIGNAL(finished(int)), s2);
connect(&machine, QStateMachine::finished, [&loop]{
qDebug() << "Finished";
loop.quit();
});
machine.addState(s1);
machine.addState(s2);
machine.setInitialState(s1);
machine.start();
dialog->show();
loop.exec();
qDebug() << "Really finished";
}
因此我们创建QEventLoop
,QStateMachine
并添加状态(初始状态和最终状态)。然后连接QDialog::finished()
信号并转换到最终状态,并将QStateMachine::finished()
信号连接到将停止事件循环的插槽。然后显示QDialog
并开始QStateMachine
。
在控制台上将打印:
成品
真的完成了