QStateMachine 在释放模式下不发出 started() 信号

QStateMachine is not emitting started() signal in release mode

我正在为设备控制器使用 QStateMachine 框架 class。它在调试模式下工作正常。但是,在释放模式下 QStateMachine::started() 信号不会被发射。下面是一个针对该问题(表单为空)的简单小部件项目。

Qt 版本 5.14.1
编译器:MSVC 2017、MinGW(均为 64 位且结果相同)

Test.pro

QT += core gui widgets 
CONFIG += c++11
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QStateMachine>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
public slots:
    void stateMachineStarted();

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QStateMachine *stateMachine;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

void MainWindow::stateMachineStarted()
{
    qDebug() << "MainWindow::stateMachineStarted()";
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    qDebug() << "MainWindow::MainWindow()";
    ui->setupUi(this);
    stateMachine = new QStateMachine;

    QState *closed = new QState;
    QState *setup = new QState;
    QState *opened = new QState;
    QState *closing = new QState;

    stateMachine->addState(closed);
    stateMachine->addState(setup);
    stateMachine->addState(opened);
    stateMachine->addState(closing);

    Q_ASSERT(connect(stateMachine, &QStateMachine::started, this, &MainWindow::stateMachineStarted));

    stateMachine->setInitialState(closed);
    stateMachine->start();
}

MainWindow::~MainWindow()
{
    qDebug() << "MainWindow::~MainWindow()";
    delete ui;
}

调试模式下的应用程序输出(我在几秒钟后关闭了表单。)

12:39:09: Starting C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Debug\debug\Test.exe ...
MainWindow::MainWindow()
MainWindow::stateMachineStarted()
MainWindow::~MainWindow()
12:39:11: C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Debug\debug\Test.exe exited with code 0

发布模式下的应用程序输出(我在几秒钟后关闭了表单。)

12:27:51: Starting C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Release\release\Test.exe ...
MainWindow::MainWindow()
MainWindow::~MainWindow()
12:27:53: C:\bin\build-Test-Desktop_Qt_5_14_2_MSVC2017_64bit-Release\release\Test.exe exited with code 0

在发布模式下,很可能没有建立连接,因为您将其包装在 Q_ASSERT 宏中。

有关详细信息,请参阅 Q_ASSERT release build semantics