Hello,
I have simple gui application. This application creates new background thread. There are some operations to execute in the thread with progress reporting to gui thread.
Some code:
backthread.h:
#ifndef BACKTHREAD_H
#define BACKTHREAD_H
#include <QThread>
#include "Counter.h"
{
public:
virtual void run();
private:
Counter counter;
};
#endif // BACKTHREAD_H
#ifndef BACKTHREAD_H
#define BACKTHREAD_H
#include <QThread>
#include "Counter.h"
class BackThread : public QThread
{
public:
virtual void run();
private:
Counter counter;
};
#endif // BACKTHREAD_H
To copy to clipboard, switch view to plain text mode
backthread.cpp:
#include "backthread.h"
void BackThread::run()
{
int i=0;
while(1)
{
counter.setValue(i);
sleep( 1 );
qDebug( "Ping!" );
i+=10;
if(i==100) i=0;
}
}
#include "backthread.h"
void BackThread::run()
{
int i=0;
while(1)
{
counter.setValue(i);
sleep( 1 );
qDebug( "Ping!" );
i+=10;
if(i==100) i=0;
}
}
To copy to clipboard, switch view to plain text mode
Counter.h:
#ifndef COUNTER_H
#define COUNTER_H
#include <QObject>
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
#endif
#ifndef COUNTER_H
#define COUNTER_H
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
#endif
To copy to clipboard, switch view to plain text mode
Counter.cpp:
#include "Counter.h"
void Counter::setValue(int value)
{
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
}
#include "Counter.h"
void Counter::setValue(int value)
{
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
}
To copy to clipboard, switch view to plain text mode
And in main windows class:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow
::MainWindow(QWidget *parent
){
ui->setupUi(this);
BackThread th;
th.start();
}
MainWindow::~MainWindow()
{
delete ui;
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
BackThread th;
th.start();
}
MainWindow::~MainWindow()
{
delete ui;
}
To copy to clipboard, switch view to plain text mode
There is Progress Bar widget in main window, and its value should be updated when Counter::m_progress changes. But I have no idea how to define slot for main window class to receive notifications from thread.
Can you help me?
Bookmarks