我正在尝试编写一个压缩gui,它创建一个用于调用压缩工具的不同线程,并使用QProcess传递参数。
当使用旧的SIGNAL / SLOT样式进行连接时,信号会被扔掉,我可以对它们做出反应,但是尝试不使用SIGNAL / SLOT进行连接不会给我带来任何回音。
class CommandProcessorMT : public QObject
{
Q_OBJECT
public:
explicit CommandProcessorMT(QObject *parent = nullptr);
bool cmdprocess(QString tool,QStringList params);
...
private:
QProcess *m_Cmdprocess;
...
private slots:
void processFinished(int exitCode,QProcess::ExitStatus exitStatus);
void processErrored(QProcess::ProcessError error);
};
void CommandProcessorMT::compressionLoop()
{
...
m_Cmdprocess = new QProcess(this);
/* Connection works */
connect(m_Cmdprocess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(processFinished(int,QProcess::ExitStatus)));
connect(m_Cmdprocess,SIGNAL(error(QProcess::ProcessError)),SLOT(processErrored(QProcess::ProcessError)));
/* Connection doesn't work */
connect(m_Cmdprocess,QOverload<int,QProcess::ExitStatus>::of(&QProcess::finished),&CommandProcessorMT::processFinished);
connect(m_Cmdprocess,QOverload<QProcess::ProcessError>::of(&QProcess::error),&CommandProcessorMT::processErrored);
while(...)
{
/* Do stuff */
m_Cmdprocess->start(tool,params);
m_Cmdprocess->waitForFinished(-1);
}
emit compDone();
}
void CommandProcessorMT::processFinished(int exitCode,QProcess::ExitStatus exitStatus)
{
qDebug() << "process Finished";
}
void CommandProcessorMT::processErrored(QProcess::ProcessError error)
{
qDebug() << "Process Error";
}
我知道waitForFinished不好,想摆脱它(这就是为什么我现在使用Signals的原因),我的信号为什么不能正确连接?
创建线程的类:
class BatchConverter : public QMainWindow
{
Q_OBJECT
public:
BatchConverter(QWidget *parent = nullptr);
~BatchConverter() override;
...
private:
Ui::BatchConverter *ui;
CommandProcessorMT *testi;
QThread *conversionThread;
...
};
BatchConverter::BatchConverter(QWidget *parent)
: QMainWindow(parent),ui(new Ui::BatchConverter)
{
testi = new CommandProcessorMT();
conversionThread = new QThread();
...
testi->moveToThread(conversionThread);
// Signals to own Slots
...
// Slots to own Signals
...
ui->setupUi(this);
setacceptDrops(true);
ui->progressBar->reset();
conversionThread->start();
}