QTimer在构造函数或静态中创建时会崩溃

qtimer crashes when created in constructor or static

本文关键字:创建 崩溃 静态 构造函数 QTimer      更新时间:2023-10-16

所以,我终于找到了这个奇怪的问题,我找不到答案。

我正在创建一个小的GUI,在单独的窗口中启动应用程序,然后使用QTimer对该应用程序的状态进行轮询。

    process_timer = new QTimer(this);
    connect(process_timer, SIGNAL(timeout()), this, SLOT(checkFlashProcess()));
    process_timer->start(100);

所以这有效。但是我宁愿每次都创建一个新的计时器,所以我将process_timer的创建放在GUI的构造函数中:

Flasher::Flasher(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Flasher)
{
    ui->setupUi(this);
    process_timer = new QTimer(this);
}

现在,这导致崩溃和输出:Qobject ::连接:无法连接(null):: timeout()to flasher :: checkflashprocess()

与此相同:

Flasher::Flasher(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Flasher),
process_timer(new QTimer)
{...

qtimer *process_timer在应用程序标题中定义。

我还尝试将process_timer定义为非动态:

    header.h:
        QTimer process_timer;
    code.cpp
    void Flasher::on_flashButton_clicked()
    {
    (...)
    hProcess = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, process_pid );
    if(hProcess)
    {
        qDebug() << "Got handle for process!";
        connect(&process_timer, SIGNAL(timeout()), this, SLOT(checkFlashProcess()));
        process_timer.start(30);
    }

这也导致崩溃。

回调:

 void Flasher::checkFlashProcess()
 {
        qDebug() << "Got handle for process!";
 }

但是为什么?我想计时器不会在构造函数中创建,但是在构造函数中创建对象不应该是问题吗?为什么静态版本也会崩溃,这是同一问题?

好的,所以看来这与qtimer无关,而是一个内存问题。我在很多地方寻找如何在Windows中获取流程处理,并且大多发现有关UNIX的来源。然后,在这两个之间,我显然将事情混合在一起,最终使用dword进行了process_pid,这似乎是在内存中的计时器之前放置的。因此,称OpenProcess造成了腐败并导致崩溃。通过再次恢复计时器来启动应用程序"修复"此应用程序后创建计时器。

又一个教训,并使用QINT64从Qprocess到OpenProcess进行PID效果很好。希望有人在想做类似的事情并可以避免麻烦时能找到这一点,感谢您踢我创建一个MCVE来隔离问题。