QtcpServer: Qt 如何获取 python 字符串到标签

QtcpServer: Qt how to get python string to label

大家好,我使用 python 向 qt 发送一个字符串,但我不知道如何在标签上显示字符串 谁能帮我??? 我的 mainwindow.cpp 是

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();

}

每次我尝试放置 socket->readall() 时它都会在我调试时崩溃

套接字之间的连接不一定是顺序的,可以随时发生,以便QtcpServer处理适当的信号,在创建新连接时我们必须使用信号newConnection

在连接到前一个信号的插槽中,我们必须使用 nextPendingConnection 通过套接字 returns 挂起的连接。

当有未决信息时,此套接字发出 readyRead 信号,并在该任务中获得所需数据。

此外,当断开连接时,它会发出断开连接的信号,在那个插槽中,我们必须删除套接字。

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();
}