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;
}
}
Related
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 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.
I have a app that uses QMdiArea.
I want the text in the statusbar to update when another QMdiAreaSubwindow becomes active.
So the text in the statusbar should become the same as the Qlabel text inside the QWidget which is been displayed inside the QMdiAreaSubwindow.
But i can't find a way to do this. Right now the statusbar only shows the text from latest created QMdiAreaSubwindow. But it won't update the text in the statusbar(With qlabel from the qwidget) when another QMdiAreaSubwindow is selected.
As you can see in the screenshot, the text in the statusbar keeps saying "test2", but I want it to change to "text" from the active QMdiAreaSubwindow.
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMdiArea>
#include <QMdiSubWindow>
#include <newwindow.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void NewSubWindow(QString name);
void createStatusBar(QString name);
private slots:
void on_actionNew_triggered();
void on_mdiArea_subWindowActivated(QMdiSubWindow *arg1);
private:
Ui::MainWindow *ui;
NewWindow *nDialog;
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mdisubwidget.h"
#include "newwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
nDialog = new NewWindow();
connect(nDialog,&NewWindow::transmit,this,&MainWindow::NewSubWindow);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::NewSubWindow(QString name) {
// new Widget to add to mdiareasubwindow
mdisubwidget *mdiwidget = new mdisubwidget();
mdiwidget->addName(name);
mdiwidget->setWindowTitle(name);
// Create new mdiAreaSubWindow
ui->mdiArea->addSubWindow(mdiwidget);
// Show mdiArea
mdiwidget->show();
}
void MainWindow::on_actionNew_triggered()
{
nDialog->show();
}
void MainWindow::on_mdiArea_subWindowActivated(QMdiSubWindow *arg1)
{
mdisubwidget *mdiwidget = new mdisubwidget(arg1->widget());
qDebug() << "name" << mdiwidget->returnName();
createStatusBar(mdiwidget->returnName());
}
void MainWindow::createStatusBar(QString name)
{
statusBar()->showMessage("chart = "+name);
}
mdisubwidget.h
#ifndef MDISUBWIDGET_H
#define MDISUBWIDGET_H
#include <QWidget>
namespace Ui {
class mdisubwidget;
}
class mdisubwidget : public QWidget
{
Q_OBJECT
public:
explicit mdisubwidget(QWidget *parent = nullptr);
void addName(QString name);
QString returnName();
~mdisubwidget();
private:
Ui::mdisubwidget *ui;
};
#endif // MDISUBWIDGET_H
mdisubwidget.cpp
#include "mdisubwidget.h"
#include "ui_mdisubwidget.h"
#include "mainwindow.h"
QString currentName;
mdisubwidget::mdisubwidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::mdisubwidget)
{
ui->setupUi(this);
}
void mdisubwidget::addName(QString name) {
ui->label_2->setText(name);
currentName = name;
}
QString mdisubwidget::returnName() {
return currentName;
}
mdisubwidget::~mdisubwidget()
{
delete ui;
}
NewWindow.h:
#ifndef NEWWINDOW_H
#define NEWWINDOW_H
#include <QWidget>
namespace Ui {
class NewWindow;
}
class NewWindow : public QWidget
{
Q_OBJECT
public:
explicit NewWindow(QWidget *parent = nullptr);
~NewWindow();
signals:
void transmit(QString name);
private slots:
void on_pushButton_clicked();
private:
Ui::NewWindow *ui;
};
#endif // NEWWINDOW_H
NewWindow.cpp:
#include "newwindow.h"
#include "ui_newwindow.h"
#include "mainwindow.h"
NewWindow::NewWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::NewWindow)
{
ui->setupUi(this);
}
NewWindow::~NewWindow()
{
delete ui;
}
void NewWindow::on_pushButton_clicked()
{
QString name = ui->lineEdit->text();
emit transmit(name);
}
ok you're using Qt Designer to connect the signal of subWindowActivated to the slot of on_mdiArea_subWindowActivated of your MainWindow, double check with qDebug in your on_mdiArea_subWindowActivated function if the name of your selected sub window appears on the console as you tried to change your current mdi sub window so follow my code snippets to find your way:
connect(ui->mdiArea, &QMdiArea::subWindowActivated, this, &DesignerWindow::activeViewChanged);
activeViewChanged():
void DesignerWindow::activeViewChanged(QMdiSubWindow *activeSubWindow)
{
// checks if there is no active sub window defined or the number of subwindows
// are zero then return
if (!activeSubWindow)
return;
if (ui->mdiArea->subWindowList().count() == 0) {
ui->itemsTree->clear();
return;
}
// defines the current Midi, View and graphical Scene when current sub window changes
currentMidi = reinterpret_cast<MidiWindow*>(activeSubWindow->widget());
currentView = reinterpret_cast<HMIView*>(currentMidi->internalView());
currentScene = reinterpret_cast<HMIScene*>(currentMidi->internalScene());
ItemsToolBar::ItemType currentType = currentScene->itemType();
itemsToolBar->selectItemType(currentType);
// updates the widgets and labels in status bar related to current midi sub window
updateScale(currentView->zoomFactor() * 100);
updateSelected();
updateItemsTree();
updateRendererType();
}
for example for updating the label in the status bar that holds the zooming factor of the current mdiSubWindow I wrote the updateScale procedure as below:
void DesignerWindow::updateScale(double _scale)
{
scale = static_cast<int>(_scale);
scaleLbl->setText(QString("%1%").arg(scale));
}
and finally I've noticed that your creating a label in status bar every time that you try to update the text in it, please avoid such a procedure and create a QLabel object and add it to your status bar as a permanent widget like below:
scaleLbl = new QLabel(this);
scaleLbl->setFrameStyle(QFrame::Sunken | QFrame::Panel);
scaleLbl->setMinimumWidth(50);
statusBar()->addPermanentWidget(scaleLbl);
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.......
}
}
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.