c++ - QT C++ 在关闭应用程序时防止运行时错误

标签 c++ qt runtime

我正在编写一个 QT 应用程序,构建和工作一切正常,但是当我关闭一个正在运行的线程的应用程序时,该应用程序关闭并显示一条消息: [运行时错误....]。

应用程序输出显示:

QThread: Destroyed while thread is still running
The program has unexpectedly finished.
The process was ended forcefully.
example crashed.

如何解决?

例子:

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QString>

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

    return a.exec();
}

主窗口.cpp

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    example = new Thread(this);
    connect(example, SIGNAL(print_line(QString)), this, SLOT(print_line2(QString)), Qt::BlockingQueuedConnection);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::print_line2(QString in)
{
    ui->textBrowser->append(in);
}

void MainWindow::on_pushButton_clicked()
{
    example->start();
}

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <Thread.h>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    Thread *example;

public slots:
    void print_line2(QString in);

private slots:

    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

线程.cpp

#include "Thread.h"
#include <windows.h>

using namespace std;

Thread::Thread(QObject *parent):
    QThread(parent)
{

}

Thread::~QThread()
{
    delete ui;
}

void Thread::print(QString in)
{
    print_line(in);
}

void Thread::run()
{
    int count = 0;
    for(;;) {
        Sleep(100);
        count += 1;
        print(QString::number(count));
    }
}

线程.h

#ifndef READINFO_H
#define READINFO_H
#include <QThread>

class Thread : public QThread
{
    Q_OBJECT

public:
   explicit Thread(QObject *parent =0);
   void print(QString in);
   void run();

signals:

   void print_line(QString x);

};

#endif

Ready example

最佳答案

问题在于,当您的应用程序关闭时,线程仍处于运行状态。

Thread::Run() 中的代码包含一个无限循环——它无法自行终止。您需要编写您的线程,以便它退出,或者至少,您需要在您的应用程序关闭之前强行终止该线程。

要强制终止,您可以像这样向 MainWindow 析构函数添加两行代码:

MainWindow::~MainWindow() 
{ 
    example->terminate(); 
    example->wait(); 
    (...)
}

关于c++ - QT C++ 在关闭应用程序时防止运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283573/

相关文章:

c++ - 创建类似 OpenGL 的图形库

c++ - 升压过程中的管道缓冲区大小

c++ - QT如何读写共享内存创建数组

delphi - 在运行时创建组件 - Delphi

java - 能否对 Java 程序进行分析以将其剥离为基本包以及 JRE?

java - 如何在运行时编译代码

c++ - 带有boost的变量参数列表?

c++ - 扩展一个简单的 makefile 以支持不同的隐式编译器标志

qt - Qt Installer Framework 可以返回失败退出代码吗?

c++ - qmake 自动生成的 Makefile 编译器设置不正确