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

时间:2015-05-20 05:22:31

标签: c++ qt ffmpeg

这里我想通过ffmpeg.exe制作录音机。

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

现在,我想使用GUI来控制重新编码器(ffmpeg.exe)。我在这里选择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??
}

我有一些想法吗?

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

1 个答案:

答案 0 :(得分:1)

以下对我来说很好:

#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
  4. 如果有帮助,请告诉我