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!
Related
So i am using the combobox on QT, in the combobox i added two devices names and i wanted to change the name in combobox to send data via radiobox to my port i tried the if statment but it doesn't work.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include <QMessageBox>
QSerialPort serial;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial.setPortName("COM3");
serial.setBaudRate(QSerialPort::Baud19200);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
ui->comboBox->addItem("SP157B");
ui->comboBox->addItem("JSP");
}
void MainWindow::on_pushButton_clicked()
{
if(ui->comboBox->currentText())
{
if(ui->radioButton->isChecked())
{
QByteArray Rouge("\x15\x7B\x1A\xAA");
serial.write(Rouge);
QString t = ui->label->text();
ui->label->setText(t+"\n15 7B 1A AA");
}
if(ui->radioButton_2->isChecked())
{
QByteArray Vert("\x15\x7B\x19\xA9"); //allume en vert
serial.write(Vert);
}
if(ui->radioButton_3->isChecked())
{
QByteArray Orange("\x15\x7B\x1B\xAB");
serial.write(Orange);
}
}
}
I just tried the following code. But the slot function is not working. The connection is OK and I found out it by qDubug. The console output is as follows.
[ZDSGuard] 32 DllMain hook strProductName2 : C:\qt_example\build-
serial_test-Desktop_Qt_5_13_1_MinGW_32_bit-Debug\debug\serial_test.exe-1
ddd
ss
ccc
As you can find, aaa is not printed out. If the slot function works fine, it should be printed.
Please let me know if somebody finds out what is wrong.
Thanks in advance.
[ZDSGuard] 32 DllMain hook strProductName2 : C:\qt_example\build-
serial_test-Desktop_Qt_5_13_1_MinGW_32_bit-Debug\debug\serial_test.exe-1
ddd
ss
ccc
Serial Communication Code
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>
#include <QLabel>
QSerialPort *serial;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort();
serial->setPortName("COM4");
serial->setBaudRate(QSerialPort::Baud115200);
serial->setFlowControl(QSerialPort::NoFlowControl);
serial->setParity(QSerialPort::NoParity);
serial->setDataBits(QSerialPort::Data8);
serial->setStopBits(QSerialPort::OneStop);
if (serial->open(QIODevice::ReadWrite))
ui->label->setText("bb");
if (QObject::connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived())))
qDebug()<< "ddd";
//ui->label->setText("aa");
qDebug() << "ss";
}
MainWindow::~MainWindow()
{
delete ui;
serial->close();
}
void MainWindow::serialReceived()
{
QByteArray BA;
BA=serial->readAll();
ui->label->setText("aa");
//printf(BA);
qDebug()<<"aaa";//BA;
}
QSP has bug in Qt 5.13.1. Use or Qt 5.13.0, or wait for a newest versions (5.13.2 / 5.12.6).
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!
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. .