gpt4 book ai didi

c++ - 多线程在QT中不起作用

转载 作者:行者123 更新时间:2023-11-30 05:34:49 25 4
gpt4 key购买 nike

我正在使用 GUI 在 QT 中开发 C++ 应用程序。为了使 GUI 始终响应,我为其他阻塞进程创建了一个线程。但是,应用程序正在等待阻塞过程,因此 GUI 没有响应。创建阻塞进程的线程是错误的方法吗?或者它在QT中不起作用?如果是这样,如何使 GUI 响应?请举个例子。

最佳答案

这是一个带有响应式 GUI 的多线程应用程序的简单示例:

主要.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 <QPushButton>
#include <QLineEdit>
#include <QThread>

class Worker : public QThread
{
protected:
/// Wait 3s which simulates time demanding job.
void run() { sleep(3); }
};

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow(QWidget *parent = 0);

public slots:
void doJob(bool);
void jobFinished();

private:
Worker worker;
QLineEdit *line;
QPushButton *button;
int counter;
};

#endif // MAINWINDOW_H

主窗口.cpp

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

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
line(new QLineEdit()),
button(new QPushButton()),
counter(0)
{
line->setDisabled(true);
line->setAlignment(Qt::AlignRight);
line->setText(QString::number(counter));
button->setText("Push");

connect(button, SIGNAL(clicked(bool)), this, SLOT(doJob(bool)));
connect(&worker, SIGNAL(finished()), this, SLOT(jobFinished()));

QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(line);
layout->addWidget(button);
QWidget *window = new QWidget();
window->setLayout(layout);
setCentralWidget(window);
}

void MainWindow::doJob(bool)
{
// Only one thread is running at a time.
// If you want a thread pool, the implementation is up to you :)
worker.start();

// Uncomment to wait. If waiting, GUI is not responsive.
//worker.wait();
}

void MainWindow::jobFinished()
{
++counter;
line->setText(QString::number(counter));
}

Qt 有很好的多线程支持。您可能做错了什么,如果您不提供任何代码,我们将无法帮助您。有很多方法可以实现“响应式”GUI! (包括很多方法如何实现另一个线程!)

关于c++ - 多线程在QT中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34086072/

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