I created a connection between server and client, the connection works fine in console, but i coudn't connect my QTcpServer class to GUI with signals and slots. Here is my code :
ServerTCP.cpp
ServerTcp :: ServerTcp (QWidget *parent)
{
listen(QHostAddress::Any,4000);
QObject:: connect(this, SIGNAL(newConnection()),
this, SLOT(connectionRequest()));
}
void ServerTcp :: connectionRequest()
{
emit IHM_connection();
clientConnection = nextPendingConnection();
QObject:: connect(clientConnection, SIGNAL(readyRead()),
this, SLOT(read()));
}
void ServerTcp::read()
{
QString ligne;
while(clientConnection->canReadLine())
{
ligne = clientConnection->readLine();
emit IHM_text(ligne);
}
QTextStream text(clientConnection);
}
ManinWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(&server,SIGNAL(IHM_connetion()),this,SLOT(connectionRequested()));
QObject::connect(&server,SIGNAL(read(QString)),this,SLOT(print_text(QString)));
}
void MainWindow::on_quitButton_clicked()
{
qApp->quit();
}
void MainWindow::print_text(QString text){
ui->log->append("message : " + text);
}
void MainWindow::connectionRequested(){
ui->log->append("connection OK!");
}
MainWindow::~MainWindow()
{
delete ui;
}
You have a typo in connect method: IHM_connetion
QObject::connect(&server,SIGNAL(**IHM_connetion**())
while the emitted signal is:
emit IHM_connection()
QObject:connect returns a bool value which indicates if signal-slot connection was successful. Checking this value (for example, with Q_ASSERT) is a good practice and can save you a lot of time in case of typos like this. .
Related
I have a STM32 and it would send and receive UDP packets successfully with hercules_3-2-8.
Now I have this simple code in QT, it can send UPD packets, But it would not receive any thing, the readyRead slot would never be called,
MyUDP::MyUDP(QObject *parent) : QObject(parent)
{
socket = new QUdpSocket(this);
socket->bind(QHostAddress("192.168.1.100"),2000);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
}
void MyUDP::SayHello(){
QByteArray Data;
Data.append("Hello from ASiDesigner");
socket->writeDatagram(Data,QHostAddress("192.168.1.100"),2000);
qDebug()<<"Hi Nitrogen";
}
void MyUDP::readyRead(){
QByteArray Buffer;
Buffer.resize((socket->pendingDatagramSize()));
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort);
qDebug()<<"Message from: "<<sender.toString();
qDebug()<<"Message port: "<<senderPort;
qDebug()<<"Message: "<<Buffer;
}
The mainwindow.cpp file content
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myudp.h"
MyUDP Server;
MyUDP client;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
client.SayHello();
}
The problem was solved by moving all the related UDP functions into the mainwindow.cpp file, Maybe it's related to priories in QT!
I am trying to learn how to use Multi-threading in Qt and put it to use in QtWidget applications. So I have setup this simple test case.
MainWindow
This form has some buttons and each button will execute another form (a Dialog for that matter).
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->btnShowCalibrationDialog, &QPushButton::clicked,
this, [&](){
CalibrationDialog dlg;
dlg.exec();
});
}
MainWindow::~MainWindow()
{
delete ui;
}
CalibrationDialog This dialog has a QPushButton and a QTextEdit. When the button is clicked I will run a QRunnable class (comes next!)
calibrationdialog.h (I have spared you the includes and guards!)
class CalibrationDialog : public QDialog
{
Q_OBJECT
public:
explicit CalibrationDialog(QWidget *parent = nullptr);
~CalibrationDialog();
public slots:
void onBeginWorkRequested();
void onReceiveData(int data);
private:
Ui::CalibrationDialog *ui;
};
calibrationdialog.cpp
#include "worker.h"
CalibrationDialog::CalibrationDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CalibrationDialog)
{
ui->setupUi(this);
connect(ui->btnBegin, &QPushButton::clicked,
this, &CalibrationDialog::onBeginWorkRequested);
}
CalibrationDialog::~CalibrationDialog()
{
delete ui;
}
void CalibrationDialog::onBeginWorkRequested()
{
qDebug() << "CalibrationDialog::onBeginWorkRequested()" << "on" << QThread::currentThreadId();
Worker* worker = new Worker();
QThreadPool* pool = QThreadPool::globalInstance();
connect(worker, &Worker::reportProgress,
this, &CalibrationDialog::onReceiveData);
pool->start(worker);
pool->waitForDone();
}
void CalibrationDialog::onReceiveData(int data)
{
ui->teResults->append(QString::number(data));
ui->teResults->ensureCursorVisible();
}
Worker And this is some runnable...I want to report the progress so that is shows up in the textedit of the dialog in a reponsive manner!
worker.h
class Worker : public QObject, public QRunnable
{
Q_OBJECT
public:
explicit Worker(QObject *parent = nullptr);
void run() override;
private:
int mProgress = 0;
signals:
void reportProgress(int progress);
};
worker.cpp
Worker::Worker(QObject *parent) : QObject(parent)
{
}
void Worker::run()
{
qDebug() << "Worker is running #" << QThread::currentThreadId();
while(true) {
mProgress += 100;
emit reportProgress(mProgress);
QThread::msleep(500);
}
}
I see in the debugger that control goes in to the while loop...but the signal is not being handled by the dialog! I mean the textedit stays empty!
I tried to read documentationand search online...I came to the conclusion that my problem lies in the waste land of thread affinity....but I have no idea if that is the case and if that is, how to solve it. Please assist!
remove pool->waitForDone();, never use waitForX methods in a GUI since they are blocking preventing signals from doing their job.
I'm following this example http://doc.qt.io/qt-5/qtwebsockets-echoserver-example.html but I can't figure out how to send a message to client after the connection has been made.
This seems to work but only when it's inside a function from another class.
void EchoServer::processTextMessage(QString message)
{
m_clients.at(0)->sendTextMessage("test");
}
Where / How should I put the code to get it working?
e. g. How to send a message to client after a button has been pressed in MainWindow?
This is working
void EchoServer::processTextMessage(QString message)
{
m_clients.at(0)->sendTextMessage("test");
}
This isn't working
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_clients.at(0)->sendTextMessage("test");
}
Neither this
void MainWindow::myclicked()
{
m_clients.at(0)->sendTextMessage("test");
}
I got it working. Here is the code:
QWebSocket *messageSocket;
void EchoServer::onNewConnection()
{
QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();
connect(pSocket, &QWebSocket::textMessageReceived, this, &EchoServer::processTextMessage);
connect(pSocket, &QWebSocket::disconnected, this, &EchoServer::socketDisconnected);
m_clients << pSocket;
messageSocket=pSocket;
}
void MainWindow::myclicked()
{
if (messageSocket)
{
messageSocket->sendTextMessage("test");
}
}
hello everyone I use python send a string to qt but i do not know how show the string on a label can anyone help me ???
my mainwindow.cpp is
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer *timer=new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(showTime()));
timer->start();
tcpServer.listen(QHostAddress::Any,42207);
//QByteArray Msg= tcpSocket->readAll();
readMessage();
}
void MainWindow::showTime()
{
QTime time=QTime::currentTime();
QString time_text=time.toString("hh:mm:ss");
ui->Digital_clock->setText(time_text);
QDateTime dateTime = QDateTime::currentDateTime();
QString datetimetext=dateTime.toString();
ui->date->setText(datetimetext);
}
void MainWindow::readMessage()
{
ui->receivedata_2->setText("no connection yet");
if(!tcpServer.listen(QHostAddress::Any,42207))
ui->receivedata_2->setText("waitting!");
//QByteArray Msg= tcpSocket->readAll();
}
every time i try to put socket->readall() it will get crashed when i debug
The connection between sockets is not necessarily sequential, can occur at any time so that QtcpServer handles appropriate signals, when creating a new connection we must use the signal newConnection.
In the slot that connects to the previous signal we must use nextPendingConnection that returns a pending connection through a socket.
This socket issues the readyRead signal when there is pending information, and in that task you get the data you want.
Also when disconnected this emits the signal disconnected, in that slot we must eliminate the socket.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTcpServer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void newConnection();
void readyRead();
void disconnected();
private:
Ui::MainWindow *ui;
QTcpServer* tcpServer;
};
#endif // MAINWINDOW_H
mainwindow.h
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTcpSocket>
#include <QLabel>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::newConnection);
if(!tcpServer->listen(QHostAddress::Any,42207)){
qDebug() << "Server could not start";
}
else{
qDebug() << "Server started!";
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::newConnection()
{
QTcpSocket *socket = tcpServer->nextPendingConnection();
connect(socket, &QTcpSocket::readyRead, this, &MainWindow::readyRead);
connect(socket, &QTcpSocket::disconnected, this, &MainWindow::disconnected);
}
void MainWindow::readyRead()
{
QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender());
ui->receivedata_2->setText(socket->readAll());
}
void MainWindow::disconnected()
{
sender()->deleteLater();
}
I have a multiserverapp that works fine so far. I got 4 cpp files.
Main.cpp constructs the program. MainWindow.cpp constructs the ui and starts (via buttonclick) MyServer.cpp. MyServer.cpp creates a thread and starts MyThread.cpp.
My aim is to show several major steps (like the "server started", "new connection", etc..) on a textBrowser.
I pass the outputs from MyServer.cpp via emit updateUI("server started"); to mainwindow.cpp where the output gets catched by:
//Mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myserver.h"
#include "mythread.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::AppendToBrowser(const QString text)
{
ui->textBrowser->append(text);
}
void MainWindow::on_startButton_clicked()
{
MyServer* mServer = new MyServer;
connect(mServer, SIGNAL(updateUI(const QString)), this, SLOT(AppendToBrowser(const QString)));
mServer->StartServer();
ui->textBrowser->setPlainText("Server Started");
}
That works just right because the connect command is just in the mainwindow.cpp itself.
The problem starts one step "deeper" in the mythread.cpp.
I created another signal in the
//MyThread.h
signals:
void updateUI_serv(const QString text);
and connected it in the MyServer.cpp with the MainWindow.cpp.
//MyServer.cpp
#include "myserver.h"
#include "mainwindow.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::StartServer()
{
if(!this->listen(QHostAddress::Any,1234))
{
qDebug("Server Error");
}
else
{
qDebug("Server started");
}
}
void MyServer::incomingConnection(int socketDescriptor)
{
qDebug("new connection");
MyThread *thread = new MyThread(socketDescriptor,this);
MainWindow *mMain = new MainWindow;
connect(thread, SIGNAL(updateUI_serv(const QString)),mMain ,SLOT(AppendToBrowser(const QString)));
//flags thread for selfdeletion
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
//calls run
thread->start();
emit updateUI("thread started!");
}
// MyThread.cpp
#include "mythread.h"
#include "mainwindow.h"
#include "myserver.h"
MyThread::MyThread(int ID, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
emit updateUI_serv("start");
}
void MyThread::run()
{
//thread stars here
qDebug("Starting thread");
socket = new QTcpSocket();
emit updateUI_serv("hallo");
//set socketdescriptor number
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
qDebug("client connected");
exec();
}
void MyThread::readyRead()
{
QByteArray Data = socket->readAll();
QString Datain = QString::fromLatin1(Data);
qDebug("Date in:");
emit updateUI_serv("data in:");
socket->write(Data);
}
void MyThread::disconnected()
{
qDebug("Disconnected");
socket->deleteLater();
exit(0);
}
The connect command lays here "in between" the signal (updateUI_serv from mythread.cpp) and the slot (AppendToBrowser from mainwindow.cpp) file.
At this point the program crashes as soon as I try to write data (as a client via telnet) to the serverapp.
I tried to set the connect command into the mainwindow and the mythread as well, but both times I get different problems (like debugging problems, or the text does just not show up in the textBrowser).
Thanks so far.
Eventually the myServer-Object is not running in the MainThread, therefor accessing an ui element from another thread crashes your app.
You can make sure only Messages from mainThread will get displayed by adding the following code to your AppendToBrowser Slot:
if( QApplication::instance()->thread() == QThread::currentThread() )
ui->textBrowser->setPlainText("whateverTextThereShallBe");
else
return;
//You should not run into this else...
This if section checks if the current object calling the update is the mainThread. The else-section checks for erros. If you are running in the else-section you are trying to change ui-elements form a thread which is not the mainThread (UI-Thread). Connect your SIGNAL in server to another SIGNAL (SIGNAL->SIGNAL connection) and add a connect to SIGNAL(SERVER) -> SLOT(MainWindow) in your MainWindow.cpp. Eventually try your connect-call with the 5th. parameter for Queued Connection (Qt::QueuedConnection IIRC).
Ahh i got it on my own.
I solved the problem by creating a NEW function ( void forwarding(const Qstring); ) and in that function i emitted it with the ordinary emit updateUI(text); .. stuff works finaly!