我是Qt的新成员......
我有一个Qt GUI应用程序(由我编写),我们称之为QtAPP.exe 当QtAPP.exe运行时,我将使用QThread和QProcess来执行一些外部文件, 例如player.exe(用本机C编写)。
这是我的问题: 在QtAPP.exe中,有2个类, 1. QMainWindow - QtAPP.exe的核心 2. QThread - 执行外部事务的线程类
现在,如果我在QThread中得到了一个完成的()信号, 我如何强迫QMainWindow重绘自己?
希望有人能给我看一些提示,也许示例代码:) 欢迎任何建议〜
答案 0 :(得分:1)
一种解决方案是简单地将finished()信号连接到MainWindow中的一个插槽,该插槽的实现调用update()。请注意,此信号的传递将是异步的,因为发送方和接收方对象位于不同的线程中。
这是一个有效的例子:
<强>的main.cpp 强>
#include <QtGui/QApplication>
#include "stuff.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow w;
w.show();
return app.exec();
}
<强> stuff.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
<强> stuff.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");
}