Skip to content

Instantly share code, notes, and snippets.

@ksvbka
Last active October 28, 2019 16:54
Show Gist options
  • Save ksvbka/5c1a289c6484da3e7b879223b4eeb0e8 to your computer and use it in GitHub Desktop.
Save ksvbka/5c1a289c6484da3e7b879223b4eeb0e8 to your computer and use it in GitHub Desktop.
QThread demo
#include <QtWidgets>
#include <QThread>
#include <QObject>
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QTextEdit>
class Thread : public QThread
{
Q_OBJECT
public:
Thread(QObject* parent) : QThread(parent) {}
protected:
void run() override {
/* Long running operation */
Thread::sleep(3);
emit result("I <3 thread");
}
signals:
void result(const QString& data);
};
int main(int argc, char* argv[]){
QApplication a(argc, argv);
/* Simple UI*/
auto widget = new QWidget();
auto vLayout = new QVBoxLayout(widget);
auto textEdit = new QTextEdit(widget);
vLayout->addWidget(textEdit);
vLayout->addWidget(new QPushButton("click me to test blocking UI", widget));
/* Setup thread */
auto work_thread = new Thread();
QObject::connect(work_thread, &Thread::result, textEdit, &QTextEdit::append);
QObject::connect(work_thread, &Thread::finished, work_thread, &QObject::deleteLater);
work_thread->start();
widget->show();
return a.exec();
}
/* If define class QT in cpp file, have to add this include to bypass build error */
/* https://stackoverflow.com/a/41844844 */
#include "main.moc"
#-------------------------------------------------
#
# Project created by QtCreator 2019-06-17T22:08:10
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = thread-demo
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += main.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment