试图用信号将QTcpServer连接到GUI

Trying to connect QTcpServer to GUI with signals

本文关键字:连接 GUI QTcpServer 信号      更新时间:2023-10-16

我在服务器和客户端之间创建了一个连接,该连接在控制台中工作得很好,但我无法将我的QTcpServer类与信号和插槽连接到GUI。下面是我的代码:

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

您在连接方法中有一个输入错误: ihm_connection

QObject::connect(&server,SIGNAL(**IHM_connetion**())

,而发出的信号是:

 emit IHM_connection()

QObject:connect返回一个bool值,该值表示信号槽连接是否成功。检查这个值(例如,使用Q_ASSERT)是一种很好的做法,可以在出现类似这样的拼写错误时节省大量时间。