为什么这个应用程序在新线程启动时崩溃,请大家指出我是不是做错了什么..
新线程.h
#ifndef NEWTHREAD_H
#define NEWTHREAD_H
#include <QThread>
class newthread: public QThread
{
public:
newthread();
public slots:
void run();
};
#endif // NEWTHREAD_H
新线程.cpp
#include "newthread.h"
#include "mainwindow.h"
#include<QDebug>
newthread::newthread()
{
}
void newthread::run(){
qDebug()<<"thread executed";
}
主窗口.cpp
#include <QtGui>
#include "mainwindow.h"
#include"newthread.h"
MainWindow::MainWindow(QWidget *parent)
{
setupUi(this);
connect(pushButton,SIGNAL(clicked()),this, SLOT(opthread()));
}
void MainWindow::opthread(){
newthread th;
th.start();
}
在主窗口中有一个名为 ophthread() 的公共(public)插槽。如上所示,当按下主窗口中的按钮时,该插槽将触发。在其中我声明了一个名为 th 和 th.start() 的新线程对象来启动它。我做错了什么吗?
这编译没有错误。但是当运行二进制文件时,它会出错并崩溃。
我的第二个问题是,如果我需要线程在主窗口的 textEdit 上写一些文本,该怎么做。有没有可能newthread类访问主窗口类中的对象。
最佳答案
void MainWindow::opthread(){
newthread th;
th.start();
}
您正在堆栈上创建线程对象。当 opthread
函数返回时,他将被销毁。来自Qt documentation :
Deleting a running QThread (i.e. isFinished() returns false) will probably result in a program crash. Wait for the finished() signal before deleting the QThread.
您需要为新线程对象提供更长的生命周期。等待它完成不是一种选择,因为它会导致顺序执行。您要么使用类成员,要么在堆上分配线程对象。
个人观点: 不仅子类化 QThread 不是完成它的最合适的方法,我相信你根本不需要线程。
关于c++ - 新线程上的应用程序崩溃开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17400240/