簡體   English   中英

我試圖找出如何在一個簡單的Qt gui應用程序中使用線程

[英]I'm trying to figure out how to use threads in a simple Qt gui application

在我所擁有的簡單示例代碼中,有一個啟動和停止按鈕以及一個計數器。 當您按下開始時,會創建一個線程並使計數器遞增,直到您按下停止。 click事件都在工作,但是當從dialog.cpp調用它時,線程本身不會啟動,並且計數器永遠不會遞增。 任何想法為什么??

代碼來自這個人的教程,正如他在這里所做的那樣,他的工作: http//www.voidrealms.com/viewtutorial.aspx?id = 79

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include "mythread.h"
#include <QDialog>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
    MyThread *mThread;

private:
    Ui::Dialog *ui;

public slots:
    void onNumberChanged(int);

private slots:
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    mThread = new MyThread(this);
    connect(mThread,SIGNAL(NumberChanged(int)), this, SLOT(onNumberChanged(int)));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::onNumberChanged(int Number){
    ui->label->setText(QString::number(Number));
}

void Dialog::on_pushButton_clicked()
{
    mThread->start();
}

void Dialog::on_pushButton_2_clicked()
{
    mThread->Stop = true;
}

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);
    void run();
    bool Stop;

signals:
    void NumberChanged(int);

public slots:

};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"
#include <QtCore>

MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
}


void MyThread::run() {

    for (int i = 0; i < 100000; i++) {
        QMutex mutex;
        mutex.lock();
        if (this->Stop) break;
        mutex.unlock();

        emit NumberChanged(i);
    }
}

謝謝!

在查看您鏈接的網站的示例代碼后,我發現至少有兩個問題:

1) Stop成員變量未被初始化使用,將構造函數更改為應該修復您的主要問題:

MyThread::MyThread(QObject *parent) :
    QThread(parent),
    Stop(false)
{
}

2) Stop變量永遠不會被重置,所以按下開始/停止按鈕只能工作一次。 如果break語句也重置了標志,它將更好地工作:

if (this->Stop)
{
    Stop = false;
    break;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM