Reputation: 51
I created a timer in a thread and in this timer char value counts from 0 to 10. I want to display this char value on the GUI. I do not get any error but the GUI freeze when I started.
Can you help me on where I am doing wrong please?
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "mythread.h"
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
MyThread *mThread;
private:
Ui::MainWindow *ui;
public slots:
void onNumberChanged(char);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
mThread = new MyThread(this);
connect(mThread,SIGNAL(NumberChanged(char)), this, SLOT(onNumberChanged(char)));
mThread->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onNumberChanged(char Number)
{
ui->label->setText(QString::number(Number));
}
mythread.h
#include <QThread>
#include <QTimer>
#include <QObject>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void run();
signals:
void NumberChanged(char);
public slots:
void update();
private:
QTimer *timer;
};
mythread.cpp
#include "mythread.h"
#include <QtCore>
char i=45;
QString mystr = "mytext";
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
timer= new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(update()));
timer->start(10);
}
void MyThread::update()
{
for( i = 0; i<10; i++){
emit NumberChanged(i);
this->msleep(500);
}
if (i>0)
i=0;
}
void MyThread::run()
{
}
Upvotes: 0
Views: 740
Reputation: 585
you need to create your timer in the run() function, not in the constructor. because the constructor is called in GUI thread and each object that is created in this function is in GUI thread. or you can call moveToThread for your timer to move to your thread.
Upvotes: 1