Using Thread in GUI application - c++

I am making a multiple game. I need to take command from client. This means I have GUI and TcpServer. So I need to work them simultaneously. I used Thread but it doesnt work. Could you please help me to find the problem?
Summarizing: Firstly player press the "online" button. Then Oyun() Gui function runs and button connected with connectPressed() function. In this function there is a thread in order to run read the client commands when Gui is working.
Firstly I used QTimer in order to take command from Client in every 1 second. But My GUI freezed. And Then I used QThread but according to my research, QThread is not proper for GUI app. So I found Qtconcurrent, QFutureWatcher and QFuture. But my thread is still not working. I should have made a mistake somewhere.
#include <QApplication>
#include <anaclass.h>
#include <player2.h>
#include <tcpserver.h>
#include <QThread>
#include <QObject>
//#include <worker.h>
AnaClass *anaclass;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
anaclass = new AnaClass();
anaclass->show();
anaclass->Giris(); //button selection page
return a.exec();
}
#include "anaclass.h"
Puan *puanlama1;
Puan *puanlama2;
player2 *yilan2;
AnaClass::AnaClass() : QGraphicsView()
{
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setFixedSize(800,600);
scene = new QGraphicsScene;
scene->setSceneRect(0,0,800,600);
setScene(scene);
}
void AnaClass::Giris()
{
connectButton = new Button("Online");
double cxPos = this->width()/2 - connectButton->boundingRect().width()/2;
double cyPos= 425;
connectButton->setPos(cxPos, cyPos);
connect(connectButton, SIGNAL(clicked()), this, SLOT(connectPressed()));
scene->addItem(connectButton);
}
void AnaClass::Oyun()
{
scene->clear();
puanlama1 = new Puan();
puanlama1->setDefaultTextColor(Qt::blue);
puanlama1->setPos(5, 2);
scene->addItem(puanlama1);
yilan = new Yilan();
yilan->setRect(0,0,19,19);
scene->addItem(yilan);
yilan->setFlags(QGraphicsItem::ItemIsFocusable);
yilan->setFocus();
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(Qt::blue);
yilan->setBrush(brush);
if(stringButtonName == "Player2" || stringButtonName == "Online")
{
yilan->setPos(scene->width()/2 + 60, scene->height()/2);
}
else
{
yilan->setPos(scene->width()/2, scene->height()/2);
}
if(stringButtonName == "Player2" || stringButtonName == "Online")
{
yilan->playerNumber=1;
puanlama2 = new Puan();
puanlama2->setDefaultTextColor(Qt::green);
puanlama2->setPos(700, 2);
scene->addItem(puanlama2);
yilan2 = new player2();
yilan2->setRect(0,0,19,19);
scene->addItem(yilan2);
yilan2->setFlags(QGraphicsItem::ItemIsFocusable);
yilan2->setFocus();
QBrush brush2;
brush2.setStyle(Qt::SolidPattern);
brush2.setColor(Qt::green);
yilan2->setBrush(brush2);
yilan2->setPos(scene->width()/2 - 60,scene->height()/2);
}
emit emitTcp();
}
void AnaClass::connectPressed()
{
qDebug()<<"connect basildi";
server = new TCPServer();
server->Test();
stringButtonName = connectButton->buttonName;
qDebug()<<"Gelen Veri " + server->OkunanBilgi;
QFutureWatcher<void> watcher;
connect(&watcher, SIGNAL(finished()), server, SLOT(daimaOku()), Qt::QueuedConnection);
QFuture<void> deneme = QtConcurrent::run(this, &AnaClass::emitTcp);
watcher.setFuture(deneme);
Oyun();
}
}
#ifndef ANACLASS_H
#define ANACLASS_H
#include <QGraphicsScene>
#include <QGraphicsView>
#include <yilan.h>
#include <Meyve.h>
#include <QBrush>
#include <Puan.h>
#include <player2.h>
#include <QThread>
#include <label.h>
#include <QKeyEvent>
#include <button.h>
#include <QDebug>
#include <tcpserver.h>
#include <QTime>
#include <QTimer>
#include <QMutex>
//#include <worker.h>
#include <QFuture>
#include <QtConcurrent>
#include <QFutureWatcher>
class AnaClass : public QGraphicsView
{
Q_OBJECT
public:
AnaClass();
void Giris();
void Oyun();
void timerEvent(QTimerEvent *event);
void keyPressEvent(QKeyEvent *event2);
public:
Yilan *yilan;
//QThread *thread;
QGraphicsScene *scene;
Label *label1;
Button* player1Button;
Button* player2Button;
Button* connectButton;
TCPServer *server;
QTimer *timerOnline;
public:
int k=0;
int t=0;
QString stringButtonName;
signals:
void emitTcp();
public slots:
void connectPressed();
void player1Pressed();
void player2Pressed();
};
#endif // ANACLASS_H
#define TCPSERVER_H
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
#include <QObject>
#include <QTimer>
class TCPServer : public QObject
{
Q_OBJECT
public:
TCPServer(QObject* parent = nullptr);
void Test();
signals:
//void emitTcp();
public slots:
void newConnection();
void daimaOku(); // always read as english
public:
QTcpServer *server;
QTcpSocket *socket;
QTimer *timerTcp;
QString OkunanBilgi;
};
#endif // TCPSERVER_H
#include "tcpserver.h"
TCPServer::TCPServer(QObject * parent) : QObject()
{
}
void TCPServer::Test()
{
server = new QTcpServer();
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if(!server->listen(QHostAddress::Any, 1234))
{
qDebug()<<"server baslamadi";
}
else
{
qDebug()<<"server basladi";
}
//timerTcp = new QTimer();
//connect(timerTcp, SIGNAL(timeout()), this, SLOT(daimaOku()));
//emit emitTcp();
}
void TCPServer::newConnection()
{
qDebug()<<"newconnection";
socket = server->nextPendingConnection();
socket->write("Merhaba Client");
socket->flush();
socket->waitForBytesWritten(5000);
timerTcp->start(50);
}
void TCPServer::daimaOku() //alwaysread() as english
{
qDebug()<<"always read function is working";
// if(socket->state() == QAbstractSocket::ConnectedState)
// {
// qDebug()<<"Daima oku fonsiyonu soket bagli";
// socket->waitForReadyRead();
// OkunanBilgi = socket->readAll();
// qDebug()<<"Tcp daima oku :" + OkunanBilgi;
// }
}

Thank you for your comments. I solved the problem by deleting QFuture and adding connect() like below.
timerOnline = new QTimer();
connect(timerOnline, SIGNAL(timeout()), server, SLOT(daimaOku()));
timerOnline->start(500);
But I have another problem. When Client connects the server, my Gui app freezes. You can find the revised code below.
void TCPServer::daimaOku()
{
qDebug()<<"Function is running";
if(socket->state() == QAbstractSocket::UnconnectedState)
{
qDebug()<<"Socket is not connected";
}
else
{
qDebug()<<"Socket connected";
socket->waitForReadyRead();
OkunanBilgi = socket->readAll();
qDebug()<<"Tcp always read :" + OkunanBilgi;
}
}
When client is not connected, the output is:
Function is running
Socket is not connected
Socket is not connected ...
I can play the game but when client is connected, game freezes. I don't understand why.

Related

Qt widget takes a long time until it starts to receive mouse events in full screen mode on macOS

In normal screen mode, Qt widgets receive mouse events immediately after creation. In full-screen mode on macOS, however, it takes a while until the widget starts receiving those events. From my tests, it takes ~700ms on average until a widget receives its first mouse event versus ~30ms in normal screen mode. Why does it take so long for mouse events to stream in when using full-screen mode? Is there a way to force Qt to receive those events earlier? See my test in the GIF animation below.
The source code for my test follows below.
/**
* main.cpp
*/
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return QApplication::exec();
}
/**
* mainwindow.h
*/
#pragma once
#include "popupwindow.h"
#include <QWidget>
#include <QPushButton>
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
private slots:
void handleFullScreenButton();
void handleNormalScreenButton();
private:
PopupWindow* m_fullScreenWindow;
QPushButton* m_fullScreenButton;
QPushButton* m_normalScreenButton;
PopupWindow* m_normalScreenWindow;
};
/**
* popupwindow.h
*/
#pragma once
#include <QWidget>
#include <QLabel>
class PopupWindow : public QWidget
{
Q_OBJECT
public:
explicit PopupWindow(QWidget* parent = nullptr);
protected:
void mouseMoveEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
private:
void showText(const QString &text);
QLabel* m_text;
qint64 m_creationTimestamp;
bool m_eventReceived;
};
/**
* mainwindow.cpp
*/
#include "mainwindow.h"
#include <QDebug>
#include <QVBoxLayout>
MainWindow::MainWindow(QWidget *parent)
: m_normalScreenWindow(nullptr)
, m_fullScreenWindow(nullptr)
{
auto *layout = new QVBoxLayout(this);
m_normalScreenButton = new QPushButton("Popup screen");
m_fullScreenButton = new QPushButton("Popup full screen");
connect(m_normalScreenButton, &QPushButton::released, this, &MainWindow::handleNormalScreenButton);
connect(m_fullScreenButton, &QPushButton::released, this, &MainWindow::handleFullScreenButton);
layout->addWidget(m_normalScreenButton);
layout->addWidget(m_fullScreenButton);
}
void MainWindow::handleNormalScreenButton() {
m_normalScreenWindow = new PopupWindow(this);
m_normalScreenWindow->show();
m_normalScreenWindow->activateWindow();
m_normalScreenWindow->raise();
}
void MainWindow::handleFullScreenButton() {
m_fullScreenWindow = new PopupWindow(this);
m_fullScreenWindow->showFullScreen();
m_fullScreenWindow->activateWindow();
m_fullScreenWindow->raise();
}
/**
* popupwindow.cpp
*/
#include "popupwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QHBoxLayout>
PopupWindow::PopupWindow(QWidget *parent)
: m_creationTimestamp(QDateTime::currentMSecsSinceEpoch())
, m_eventReceived(false)
, m_text(nullptr)
{
setAttribute(Qt::WA_DeleteOnClose);
setMouseTracking(true);
}
void PopupWindow::mouseMoveEvent(QMouseEvent *event) {
if (m_eventReceived) {
return;
}
auto deltaTimeMs = QDateTime::currentMSecsSinceEpoch() - m_creationTimestamp;
showText(QString("First mouse event received after %1 ms.").arg(deltaTimeMs));
m_eventReceived = true;
}
void PopupWindow::mousePressEvent(QMouseEvent *event) {
showNormal();
close();
}
void PopupWindow::showText(const QString &text) {
m_text = new QLabel(text);
m_text->setStyleSheet("font: 26pt;");
auto *layout = new QVBoxLayout(this);
layout->addWidget(m_text, Qt::AlignCenter);
}

How? I show a message, while the task is running

I have the following code.
A method compress (), where I do the task of compressing an entire directory, I call this method from my button, with a QtConcurrent, as you can see. so far so good.
My question is, how can I display a message while compressing the folder is running.
I am using QuaZIP, for the compression process.
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButton_5_clicked();
private:
Ui::Widget *ui;
void compress();
public:
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QDebug>
#include <JlCompress.h>
#include <QtConcurrent/QtConcurrent>
#include <QFuture>
Widget::Widget(QWidget *parent)
: QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_5_clicked()
{
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
QFuture<void> future=QtConcurrent::run(this,&Widget::compress);
future.waitForFinished();
QGuiApplication::restoreOverrideCursor();
QMessageBox::information(this,qApp->applicationName(),"The folder was compressed successfully.");
}
void Widget::compress()
{
if(!JlCompress::compressDir("C:/Users/Mypc/Desktop/iconos.zip", "D:/images/iconos")){
QMessageBox::warning(this,qApp->applicationName(),"Error compressing folder.");
return;
}
}
I did this, but now when the backup finishes, the entire application closes.
void Widget::on_pushButton_5_clicked()
{
QMessageBox box;
// box->setWindowFlags(Qt::Dialog | Qt::SplashScreen);
box.setStandardButtons(QMessageBox::NoButton);
box.setText("Realizando una tarea!");
box.setWindowTitle(qApp->applicationName());
box.setIcon(QMessageBox::Information);
box.setAttribute(Qt::WA_DeleteOnClose);
QFutureWatcher<void> watcher;
QFuture<void> future=QtConcurrent::run(this,&Widget::compress);
watcher.setFuture(future);
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
QObject::connect(&watcher,&QFutureWatcher<void>::finished,[&](){
box.close();
box.deleteLater();
QGuiApplication::restoreOverrideCursor();
});
box.exec();
QMessageBox::information(this,qApp->applicationName(), "The folder was compressed successfully.");
}
Also try a ProgressDialog and QFutureWatcher as follows, but it doesn't compile, I get this error.
void Widget::on_pushButton_5_clicked()
{
QStringList files;
QDir dir("D:/images/iconos/uigenericicon");
files=dir.entryList(QStringList() << "*.jpg" << "*.JPG"<<"*.PNG",QDir::Files);
qInfo()<<files;
QProgressDialog pDialog;
pDialog.setLabelText("Porecessing!!");
QFutureWatcher<void> watcher;
QObject::connect(&pDialog,SIGNAL(canceled()),&watcher,SLOT(cancel()));
QObject::connect(&watcher,SIGNAL(finished()),&pDialog,SLOT(reset()));
QObject::connect(&watcher,SIGNAL(progressRangeChanged(int,int)),&pDialog,SLOT(setRange(int,int)));
QObject::connect(&watcher,SIGNAL(progressValueChanged(int)),&pDialog,SLOT(setValue(int)));
watcher.setFuture(QtConcurrent::map(files,&Widget::compress));
pDialog.exec();
if(watcher.isCanceled()){
QMessageBox::information(this,qApp->applicationName(),"You canceled.");
}else{
QMessageBox::information(this,qApp->applicationName(),"All done.");
}
}
void Widget::compress(QStringList &files)
{
if(!JlCompress::compressFiles("C:/Users/Lincoln/Desktop/iconos.zip",files)){
QMessageBox::warning(this,qApp->applicationName(),"Error al comprimir la carpeta.");
return;
}
}

menu bar functionalities aren't working in Qt

so i am writing a simple video player program and i did the same steps as the lesson i am taking but when i run the program and click on functionalities like end (which is close()) and open (open file) they dont work, i used the slot triggering as per the lesson although i saw different ways of using the menubar here but i must follow this format, here is my code:
header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QVideoWidget>
#include <QStyle>
#include <QMediaPlayer>
#include <QFileDialog >
namespace Ui {
class videoWidget;
}
class videoWidget : public QMainWindow
{
Q_OBJECT
QMediaPlayer *meinPlayer;
QPushButton *playButton;
QPushButton *stopButton;
public:
explicit videoWidget(QWidget *parent = 0);
~videoWidget();
private slots:
void listeUndTitelAktualisieren();
void on_action_End_triggered();
void on_action_ffnen_triggered();
void on_action_Stop_triggered();
void on_action_PlayBack_triggered();
void on_action_Pause_triggered();
private:
Ui::videoWidget *ui;
};
#endif // MAINWINDOW_H
cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
videoWidget::videoWidget(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::videoWidget)
{
ui->setupUi(this);
meinPlayer = new QMediaPlayer(this);
meinPlayer->setMedia(QUrl::fromLocalFile("/beispiele/topologien.wmv"));
meinPlayer->play();
}
void videoWidget::listeUndTitelAktualisieren()
{
QString titel = meinPlayer->media().canonicalUrl().toLocalFile();
ui->listWidget->addItem(titel);
this->setWindowTitle("Multimedia-Player – " + titel);
connect(meinPlayer, SIGNAL(mediaChanged(QMediaContent)), this, SLOT(listeUndTitelAktualisieren()));
}
void videoWidget::on_action_End_triggered()
{
this->close();
}
void videoWidget::on_action_ffnen_triggered()
{
QFileDialog *meinDialog = new QFileDialog(this);
meinDialog->setAcceptMode(QFileDialog::AcceptOpen);
meinDialog->setWindowTitle("Datei öffnen");
meinDialog->setNameFilters(QStringList() << "Videos (*.mp4 *.wmv)" << "Audios (*.mp3)" << "Alle Dateien (*.*)");
meinDialog->setDirectory(QDir::currentPath());
meinDialog->setFileMode(QFileDialog::ExistingFile);
if (meinDialog->exec() == QDialog::Accepted) {
QString datei = meinDialog->selectedFiles().first();
meinPlayer->setMedia(QUrl::fromLocalFile(datei));
/*QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Image"), "/home/jana", tr("Video & Audio Files (*.mp3 *.mp4 *.wmv)"));
*/
meinPlayer->play();
}
}
void videoWidget::on_action_Stop_triggered()
{
meinPlayer->pause();
}
void videoWidget::on_action_PlayBack_triggered()
{
meinPlayer->play();
}
void videoWidget::on_action_Pause_triggered()
{
meinPlayer->pause();
}
am pretty sure this instruction here:
connect(meinPlayer, SIGNAL(mediaChanged(QMediaContent)), this, SLOT(listeUndTitelAktualisieren()));
is not located where it should coz you are connecting the signal toa slot INSIDE of the SLOT implementation....
try moving that to the constructor of dein videoWidget

How to send message from child widget to parent window in Qt?

How do I send a message from a child widget to a parent window in qt?
I tried sending a signal from the child widget to the parent window in qt. When I call the function test in subwidget.cpp, the signal is sent but the mainwindow slot does not execute. How can I send the message?
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStackedWidget>
#include <QPushButton>
#include <QProcess>
#include <QDebug>
#include <subwidget.h>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void check_adb_exists();
private:
Ui::MainWindow *ui;
QStackedWidget *stack;
QPushButton *start_btn;
SubWidget *f2;
private slots:
void StartApplication();
void ReceiveCustomMessage(const QString &msg);
};
#endif // MAINWINDOW_H
subwidget.h
#define SUBWIDGET_H
#include <QWidget>
namespace Ui {
class SubWidget;
}
class SubWidget : public QWidget
{
Q_OBJECT
public:
explicit SubWidget(QWidget *parent);
~SubWidget();
void test();
private:
Ui::SubWidget *ui;
signals:
void SendCustomMessage(const QString& msg);
};
#endif // SUBWIDGET_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
// #include <formcustomnew.h>
#include <subwidget.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
stack = MainWindow::findChild<QStackedWidget *>("stackedWidget");
start_btn = MainWindow::findChild<QPushButton *>("start_btn");
stack->setCurrentIndex(0);
connect(start_btn,SIGNAL(released()),this,SLOT(StartApplication()));
f2 = new SubWidget(this);
//connect(f2,SIGNAL(SendCustomMessage(QString)),this,SLOT(ReceiveCustomMessage(QString)));
//f2->test();
//auto f1 = new FormCustomNew(this);
//connect(f1,SIGNAL(sendMessageNewMessage(QString)),this,SLOT(receiveMessage(QString)));
//f1->test();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::StartApplication(){
//check_adb_exists();
f2->test();
}
void MainWindow::ReceiveCustomMessage(const QString &msg){
qDebug("Recieved message from child");
qDebug("Message: " + msg.toLatin1());
}
void MainWindow::check_adb_exists(){
QProcess *p = new QProcess();
connect(p,&QProcess::readyReadStandardOutput,[&](){
auto data = p->readAllStandardOutput();
qDebug("Stdout: " + data);
});
connect(p,&QProcess::readyReadStandardError,[&](){
auto data = p->readAllStandardError();
qDebug("Error: " + data);
if(data.toStdString().compare("File Not Found")){
qDebug("File Not Found is the error");
}
});
QStringList args;
args << "/c dir C:\\Users\\%USERNAME%\\AppData\\Local\\Android\\Sdk";
p->setArguments(args);
p->setProgram("C:\\Windows\\System32\\cmd.exe");
p->start();
}
subwidget.cpp
#include "subwidget.h"
#include "ui_subwidget.h"
SubWidget::SubWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::SubWidget)
{
ui->setupUi(this);
qDebug("parent: " + parent->objectName().toLatin1());
connect(this,SIGNAL(SendCustomMessage(QString)),parent,SLOT(ReceiveCustomMessage(QString)));
}
SubWidget::~SubWidget()
{
delete ui;
}
void SubWidget::test(){
emit SendCustomMessage("trial message");
}
void SubWidget::SendCustomMessage(const QString &msg){
qDebug("Sending Message: " + msg.toLatin1());
}
Signals must not be defined in Qt.
From the Qt wiki on Signal & Slots:
Signals are automatically generated by the moc and must not be implemented in the .cpp file
Remove your implementation and this should work. However you should not be binding the signal within subclass as that reduces encapsulation and reusability (parent must have a ReceiveCustomMessage(QString) slot). Instead bind it outside, as you have in your commented out code.

Display images from source directory selected by user

I have a Qt application where user selects source directory which has images (.pgm files) (any number). In the UI,
I have created a display area (QGroupBox) which has 2 QGraphicsview which displays 2 images at a time.
UI image:
Going ahead,
I want to create QGraphicsViews Widget for all the images and display 2 of them at a time. There will be a scroll bar to the right.
When user drags the scroll bar down other QGraphicsView Widgets
should be visible to the user with different images. How can i do this using Qt in C++?
PS: I am able to display two images in the display area using QGraphicsView Widget when the load images button is clicked.
#include "ui_DataViewerPage.h"
#include <iostream>
#include <QGraphicsScene>
#include <QPixmap>
#include <QThread>
#include <QSettings>
#include "DataWorker.h"
namespace Ui
{
class DataViewerPage;
}
// This is the main UI thread header and cpp file
class DataViewerPage : public QWidget
{
Q_OBJECT
public:
DataViewerPage(QWidget* parent = nullptr);
virtual ~DataViewerPage();
public slots:
void on_loadButton_clicked();
void startWorker();
void stopWorker();
void displayImage(QString fileName);
signals:
void startLoadingImages();
private:
Ui::DataViewerPage* ui;
DataWorker* worker;
QSettings settings;
// Worker thread handles data processing away from ui thread
QThread workerThread;
QSharedPointer<QGraphicsScene> ptr_scene;
QSharedPointer<QGraphicsScene> ptr_scene2;
int currentDisplayNum;
};
#include "DataViewerPage.h"
DataViewerPage::DataViewerPage(QWidget* parent)
: QWidget(parent), worker(nullptr), ui(new Ui::DataViewerPage)
{
ui->setupUi(this);
ui->Display->setVisible(true);
ptr_scene = QSharedPointer<QGraphicsScene>(new QGraphicsScene(this));
ptr_scene2 = QSharedPointer<QGraphicsScene>(new QGraphicsScene(this));
}
DataViewerPage::~DataViewerPage()
{
workerThread.quit();
workerThread.wait();
workerThread.terminate();
if (worker)
{
delete worker;
}
delete ui;
}
void DataViewerPage::on_loadButton_clicked()
{
ui->Display->setVisible(true);
ui->loadButton->setDisabled(true);
emit startLoadingImages();
}
void DataViewerPage::stopWorker()
{
workerThread.quit();
workerThread.wait();
workerThread.terminate();
if (worker)
{
delete worker;
worker = nullptr;
}
}
void DataViewerPage::startWorker()
{
stopWorker();
worker = new DataWorker();
worker->moveToThread(&workerThread);
connect(this, &DataViewerPage::startLoadingImages, worker, &DataWorker::startLoadingImages);
connect(worker, &DataWorker::displayImage, this, &DataViewerPage::displayImage);
workerThread.start();
currentDisplayNum = 0;
}
void DataViewerPage::displayImage(QString fileName)
{
QPixmap pixelMap(fileName.toStdString().c_str()); // <- path to image file
switch (currentDisplayNum)
{
case 0:
ptr_scene->addPixmap(pixelMap);
ui->img1->setScene(ptr_scene.get());
break;
case 1:
ptr_scene2->addPixmap(pixelMap);
ui->img2->setScene(ptr_scene2.get());
break;
default:
break;
}
currentDisplayNum++;
}
// This is the worker thread header and cpp file.
#pragma once
#include <QThread>
#include <QSettings>
#include <filesystem>
class DataWorker : public QObject
{
Q_OBJECT
public:
DataWorker();
~DataWorker();
public slots:
void startLoadingImages();
signals:
void displayImage(QString fileName);
private:
QSettings settings;
std::string path;
};
#include "DataWorker.h"
#include <iostream>
#include <QImage>
DataWorker::DataWorker()
{
path = settings.value("dataDir").toString().toStdString();
}
DataWorker::~DataWorker()
{
}
void DataWorker::startLoadingImages()
{
std::cout << "startloadingImages called..." << std::endl;
int iCount = 0;
for (const auto& entry : std::filesystem::directory_iterator(path))
{
QString imgPath = QString::fromStdString(entry.path().string());
emit displayImage(imgPath);
iCount++;
if(iCount > 1)
break; // Right now do it for two only.......
}
}