-1

大家好,我使用 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() 时它都会在我调试时崩溃

4

1 回答 1

0

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

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

当有待处理的信息时,此套接字会发出readyRead信号,并且在该任务中您可以获得所需的数据。

同样,当断开连接时,这会发出断开连接的信号,在那个插槽中,我们必须消除套接字。

主窗口.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

主窗口.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();
}
于 2017-07-04T21:00:13.337 回答