gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:14 25 4
gpt4 key购买 nike

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

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

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

我使用QProcess来执行它,你会看到下面的内容。

但我不知道如何终止这个过程。

代码 list :main.cpp 很简单。

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

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

return a.exec();
}

主窗口.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

主窗口.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

如果有帮助请告诉我

关于c++ - 如何在 GUI 中通过按钮或键盘使 QProcess 停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30340866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com