0

我是Qt的新手...

我有一个 Qt GUI 应用程序(由我编写),我们称之为 QtAPP.exe 当 QtAPP.exe 运行时,我将使用 QThread 和 QProcess 执行一些外部文件,例如 player.exe(用原生 C 编写)。

这是我的问题:在 QtAPP.exe 中,有 2 个类,1. QMainWindow - QtAPP.exe 的核心 2. QThread - 执行外部事物的线程类

现在,如果我在那个 QThread 中得到了一个finished() 信号,我该如何强制 QMainWindow 重新绘制自己?

希望有人能给我一些提示,也许是示例代码:) 欢迎任何建议~

4

1 回答 1

1

一种解决方案是简单地将finished() 信号连接到MainWindow 中的一个槽,该槽的实现调用update()。请注意,此信号的传递将是异步的,因为发送者和接收者对象位于不同的线程中。

这是一个工作示例:

主文件

#include <QtGui/QApplication>
#include "stuff.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow w;
    w.show();
    return app.exec();
}

东西.h

#ifndef STUFF_H
#define STUFF_H

#include <QtGui/QMainWindow>
#include <QtCore/QThread>

class QLabel;

class Thread : public QThread
{
    Q_OBJECT
public:
    Thread(QObject *parent);
    void run();

private:
    void startWork();

signals:
    void workFinished();
};

class MainWindow : public QWidget
{
    Q_OBJECT
public:
    MainWindow();

public slots:
    void startWork();
    void workFinished();

private:
    QLabel* m_label;
    Thread* m_thread;
};

#endif

东西.cpp

#include <QtCore/QTimer>
#include <QtCore/QMutex>
#include <QtCore/QWaitCondition>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLabel>
#include "stuff.h"

#include <QDebug>

// Global variables used for ITC
QWaitCondition buttonPressed;
QMutex mutex;

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

}

void Thread::run()
{
    qDebug() << "Thread::run" << QThread::currentThreadId();
    while (1) {
        mutex.lock();
        buttonPressed.wait(&mutex);
        mutex.unlock();
        startWork();
    }
}

void Thread::startWork()
{
    qDebug() << "Thread::startWork" << QThread::currentThreadId();
    // Simulate some long-running task
    sleep(3);
    // Emit a signal, which will be received in the main thread
    emit workFinished();
}


MainWindow::MainWindow()
    :   m_label(new QLabel(this))
    ,   m_thread(new Thread(this))
{
    QPushButton *button = new QPushButton("Start", this);
    connect(button, SIGNAL(pressed()), this, SLOT(startWork()));

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(button);
    layout->addWidget(m_label);
    setLayout(layout);

    // Create connection across thread boundary
    connect(m_thread, SIGNAL(workFinished()), this, SLOT(workFinished()));

    m_thread->start();
}

void MainWindow::startWork()
{
    // Signal the thread to tell it that the button has been pressed
    mutex.lock();
    m_label->setText("Started");
    buttonPressed.wakeAll();
    mutex.unlock();
}

void MainWindow::workFinished()
{
    qDebug() << "MainWindow::workFinished" << QThread::currentThreadId();
    m_label->setText("Finished");
}
于 2010-04-14T12:08:21.490 回答