在Qt中使用多线程调用cmd执行python脚本可以通过以下步骤实现:
- 创建一个继承自QThread类的子类,重写其run()函数,在其中调用cmd命令执行python脚本。
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
protected:
void run() override;
private:
QString m_cmd;
};
MyThread::MyThread(QObject *parent)
: QThread(parent)
{
}
void MyThread::run()
{
QProcess process;
process.start(m_cmd);
process.waitForFinished(-1);
}
- 在需要执行python脚本的地方创建该子类的对象,设置要执行的cmd命令并启动该线程。
MyThread thread;
thread.m_cmd = "python script.py";
thread.start();
需要注意的是,在使用多线程时涉及到GUI界面的更新等操作时,需要使用信号与槽机制进行通信。在上述代码中,可以在MyThread类中定义一个信号,当线程执行完毕后发送该信号,然后在主线程中连接该信号到某个槽函数中,以便在主线程中更新GUI界面。
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
signals:
void finished();
protected:
void run() override;
private:
QString m_cmd;
};
MyThread::MyThread(QObject *parent)
: QThread(parent)
{
}
void MyThread::run()
{
QProcess process;
process.start(m_cmd);
process.waitForFinished(-1);
emit finished();
}
在主线程中连接该信号到槽函数并启动线程。
MyThread thread;
thread.m_cmd = "python script.py";
connect(&thread, &MyThread::finished, this, &MainWindow::onThreadFinished);
thread.start();
在槽函数中更新GUI界面等操作。
void MainWindow::onThreadFinished()
{
// do something
}