[英]C++ Crash/exception handler in Qt application with thread support on Windows
[英]Application crash on new thread starts
為什么此應用程序在新線程啟動時崩潰,請somybody指出我做錯了什么。
newthread.h
#ifndef NEWTHREAD_H
#define NEWTHREAD_H
#include <QThread>
class newthread: public QThread
{
public:
newthread();
public slots:
void run();
};
#endif // NEWTHREAD_H
newthread.cpp
#include "newthread.h"
#include "mainwindow.h"
#include<QDebug>
newthread::newthread()
{
}
void newthread::run(){
qDebug()<<"thread executed";
}
主窗口
#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()的公共插槽。 如上圖所示,當按下主窗口中的按鈕時,該插槽將被觸發。 在其中ii聲明了一個名為th和th.start()的新線程對象來啟動它。 我做錯了嗎?
這個拼寫沒有錯誤。 但是當運行二進制文件時,它會給出錯誤並崩潰。
我的第二個問題是,如果我需要線程在主窗口的textEdit上寫一些文本,該怎么做。 mainwindow類中是否可能有newthread類訪問對象。
void MainWindow::opthread(){
newthread th;
th.start();
}
您正在堆棧上創建線程對象。 函數opthread
返回時,他將被銷毀。 從Qt文檔中 :
刪除正在運行的QThread(即isFinished()返回false)可能會導致程序崩潰。 在刪除QThread之前,請等待finish()信號。
您需要為newthread對象提供更長的使用壽命。 等待它完成不是一個選擇,因為它將導致順序執行。 您可以使用類成員,也可以在堆上分配線程對象。
個人觀點:不僅子類化QThread並不是完成它的最合適方法,而且我相信您根本不需要線程。
當您使用以下命令創建線程時:
newthread th;
然后它將超出范圍並被刪除,這不是您想要的。 您需要動態創建對象:-
newthread* th = new newthread;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.