好多时候,我们运算在子线程,控制和监控在界面,即主线程。
新建一个myThread,继续自QThread
myThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
//#include <QObject>
#include <QThread>
#include <QDebug>
class myThread : public QThread
{
Q_OBJECT
public:
explicit myThread(QThread *parent = nullptr);
void run();
signals:
void setDoubleValue(double val);
};
#endif // MYTHREAD_H
myThread.cpp
#include "mythread.h"
myThread::myThread(QThread *parent) : QThread(parent)
{
}
void myThread::run()
{
qDebug() << "start thread run";
double val = .0;
for(int i=0; i< 1000 ; i++)
{
for(int j=0; j< 10; j++)
{
val = i%9 + 0.5;
//qDebug() << "i: " << i << " j: " << j << " val: " << val;
emit setDoubleValue(val);
msleep(100);
}
}
qDebug() << "finish thread run";
}
mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "mythread.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
myThread *mT;
private slots:
void receiveDoubleValue(double val);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "opencv001.h"
#include <qwt_dial_needle.h>
#include <qwt_dial.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QwtDialSimpleNeedle *needle = new QwtDialSimpleNeedle(QwtDialSimpleNeedle::Arrow );
ui->Dial->setNeedle(needle);
mT = new myThread();
connect(mT, &myThread::setDoubleValue, this, &MainWindow::receiveDoubleValue);
mT->start();
opencv001 mCV;
cv::Mat img = mCV.test3();
int w = img.cols;
int h = img.rows;
int i, j;
QImage *Image = new QImage(w, h, QImage::Format_RGB888);
for(i=0;i<h;i++)
{
unsigned char *ptr = img.ptr<unsigned char>(i);
for(j=0;j<w*3;j+=3)
{
Image->bits()[(Image->bytesPerLine()*i)+(j+2)] = ptr[j+2];
Image->bits()[(Image->bytesPerLine()*i)+(j+1)] = ptr[j+1];
Image->bits()[(Image->bytesPerLine()*i)+(j)] = ptr[j];
}
}
ui->label->setPixmap(QPixmap::fromImage(*Image).scaled(ui->label->size()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::receiveDoubleValue(double val)
{
ui->Knob->setValue(val);
//qDebug() << "receive: " << val;
}
这样,通过:
connect(mT, &myThread::setDoubleValue, this, &MainWindow::receiveDoubleValue),把线程中的变化计算结果就可以显示到主界面上,线程中的计算就不会影响主线程的显示。
多谢,亲爱的美美。