如何使按钮作为线程QT5运行函数

时间:2019-07-30 19:13:38

标签: c++ windows qt5

我有一个窗口,其中有一个需要运行线程的按钮,但我找不到如何做到这一点。

mainwindow.h

#include <QWidget>
class mainWindow : public QWidget
{
    Q_OBJECT
    //here are defined some variables
 public:
    mainWindow(QWidget *parent = 0);
    ~mainWindow();
    void createUI();
    void process();
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include <QWidget>
#include <QPushButton>
#include <QProcess>
#include <QByteArray>
#include <QTextCodec>
#include <QString>
#include <QDebug>
#include "mainwindow.h"

mainWindow::mainWindow(QWidget *parent) : QWidget(parent)
{
    createUI();
}


mainWindow::~mainWindow()
{

}
void mainWindow::createUI(){
    //here I create the look of the window
     QPushButton buttonsearch = new QPushButton("Start process", this);
     buttonsearch->setToolTip("Start process");
     buttonsearch->setGeometry(200, 290, 100, 30);
     connect(buttonsearch, &QPushButton::clicked, [this]() {process(); });
}

void mainWindow::process(){
    process->setProcessChannelMode(QProcess::MergedChannels);
    process->start("\"D:\\YTDownloader\\youtube-dl.exe\" -e --no-playlist https://www.youtube.com/watch?v=6V-wwfuxZxw);
    process->waitForReadyRead();
    QByteArray a = process->readAllStandardOutput();
    QTextCodec* utfCodec = QTextCodec::codecForName("UTF-8");
    QString processStdout = utfCodec->toUnicode(a);
    qDebug() << processStdout;
}

main.cpp

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

int main(int argl,char *argv[])
{
    QApplication app(argl,argv);

    mainWindow *window = new mainWindow();
    window->setWindowTitle("Test");
    window->setFixedSize(700, 335);
    window->show();

    return app.exec();
}

我查看了QThread文档,但是在这些示例中,我没有弄清楚如何将函数作为线程运行。单击process()时,我尝试将buttonsearch函数作为线程运行。谢谢您的帮助!

0 个答案:

没有答案