close
For the purpose of using QThread class, you have to include <QThread>
and also wanna communicate with main UI, mainwindow.h should be added.
shownumber.h
#ifndef SHOWNUMBER_H
#define SHOWNUMBER_H
#include <QMainWindow>
#include <QThread>
#include <mainwindow.h>
class ShowNumber:public QThread
{
Q_OBJECT
public:
ShowNumber(MainWindow *gui);
~ShowNumber();
// to override run method
void run();
// is the job running
bool running;
int counter;
// in order to notify subscribers (mainwindow)
signals:
void signalUpdateUI();
// callback function
public slots:
void slotUpdateUI();
public:
MainWindow *m_gui;
};
#endif // SHOWNUMBER_H
shownumber.cpp
#include "shownumber.h"
ShowNumber::ShowNumber(MainWindow *gui)
{
running =true;
this->m_gui = gui;
connect(this, SIGNAL(showNum()), this, SLOT(slotUpdateUI()));
}
ShowNumber::~ShowNumber()
{
}
void ShowNumber::run()
{
while(running)
{
counter++;
emit signalUpdateUI();
msleep(1);
}
}
void ShowNumber::slotUpdateUI()
{
m_gui->shownumberDisp();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
public:
void shownumberDisp();
public slots:
void shownumberStart();
void shownumberStop();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "shownumber.h"
ShowNumber::ShowNumber(MainWindow *gui)
{
running =true;
this->m_gui = gui;
connect(this, SIGNAL(signalUpdateUI()), this, SLOT(slotUpdateUI()));
}
ShowNumber::~ShowNumber()
{
}
void ShowNumber::run()
{
while(running)
{
counter++;
emit signalUpdateUI();
msleep(1);
}
}
void ShowNumber::slotUpdateUI()
{
m_gui->shownumberDisp();
}
mainwindow.ui
References
1. Qt子執行緒如何更新UI,完整的程式碼示例,有圖有真相
2. How to Create Threads in Linux (With a C Example Program)
全站熱搜
留言列表