如何在 GUI 中通过按钮或键盘使 QProcess 停止?

How to make QProcess stop by button or keyboard in GUI?

这里我想ffmpeg.exe做一个录音机。

并且,我找到了命令行,成功运行并生成了视频文件。我知道在键盘上按 "Esc" 或 "q" 可以终端

现在,我想用GUI来控制recoder(ffmpeg.exe)。我这里是select Qt,工作环境是windows 7 sp1.

我用QProcess来执行,你会看到下面的。

但我不知道该进程的终止。

代码列表: main.cpp很简单。

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QProcess>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    QProcess *pro;
    QString recorder;
    QString outputName;
    QString options;

private slots:
    void startRecode();
    void stopRecode();
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"

#include <QProcess>
#include <QTest>
#include <QPushButton>
#include <QVBoxLayout>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    pro(new QProcess)
{
    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString("yyyy-MM-dd-hh_mm_ss");

    recorder = "E:\bin\ffmpeg.exe";
    outputName = current_date + ".mp4";
    options = "-f gdigrab -framerate 6 -i desktop -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -hide_banner -report";
    //-t 00:00:05"; this option can limit the process running time, and work well no GUI, but I don't want to use given time to stop recording.

    QWidget *centerWindow = new QWidget;
    setCentralWidget(centerWindow);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    QPushButton *startButton = new QPushButton("start recording");
    QPushButton *stopButton = new QPushButton("stop recording");
    mainLayout->addWidget(startButton);
    mainLayout->addWidget(stopButton);

    centerWindow->setLayout(mainLayout);

    connect(startButton, SIGNAL(clicked()), this, SLOT(startRecode()));
    connect(stopButton, SIGNAL(clicked()), this, SLOT(stopRecode()));
}

MainWindow::~MainWindow()
{
    delete pro;
}

void MainWindow::startRecode()
{
    pro->execute(QString(recorder + " " +options +" " + outputName));
}

void MainWindow::stopRecode(){
    pro->terminate(); // not work
    //pro->close(); // not work, too
    //pro->kill(); // not work, T_T

    //how to terminate the process by pushbutton??
}

对我有什么想法吗?

或者,我的录音机还有其他解决方案吗?

以下对我来说工作正常:

#include <QTimer>
#include <signal.h>
[...]
int thisPid = pro->pid();

kill(thisPid, SIGINT);
QTimer::singleShot( 2000, pro, SLOT( tryTerminate() ) );
QTimer::singleShot( 5000, pro, SLOT( kill() ) );

这会先获取进程的进程id,然后

  1. 给进程发送一个中断信号(如果你在windows下就需要适配这部分)
  2. 连接一个一次性定时器,在 2 秒后执行 tryTerminate
  3. 连接一个一次性定时器,在 5 秒后执行 kill

如果有帮助请告诉我