Qt插槽连接成功,但没有被解雇

时间:2014-06-06 13:55:06

标签: qt signals-slots qtcpserver

我尝试通过newConnection()课程的QTcpServer信号拨打课程的插槽。 connect()函数返回true,但插槽未执行。

这就是我所做的:

class server : QObject
{
    Q_OBJECT

public:
    server();

    QTcpServer *srv;
    void run();

public slots:
    void handleClient();
}

绑定插槽:

void server::run()
{
    srv = new QTcpServer();

    bool status = connect(srv, SIGNAL(newConnection()), this, SLOT(handleClient()));

    // status contains true now

    srv->listen(QHostAddress::Any, port);
}

Slot的身体:

void server::handleClient()
{
        /* This code is not being executed */
        qDebug() << "zxc";
        QMessageBox msg;
        msg.setText("zxc");
        msg.exec();
}

为什么不起作用?

1 个答案:

答案 0 :(得分:2)

我不太确定你做错了什么尝试在继承行(public)中添加: public QObject

以下代码适用于我:

<强> server.hpp

#ifndef _SERVER_HPP_
#define _SERVER_HPP_
#include <QtNetwork>

class Server : public QObject
{
  Q_OBJECT
  public:
    Server();
  private slots:
    void handleClient();
  private:
    QTcpServer* mServer;
};
#endif

<强> server.cpp

#include "server.hpp"

Server::Server() : mServer(new QTcpServer())
{
  connect(mServer, SIGNAL(newConnection()), this, SLOT(handleClient()));
  mServer->listen(QHostAddress::Any, 10000);
}

void Server::handleClient()
{
  while (mServer->hasPendingConnections())
  {
    QTcpSocket* skt = mServer->nextPendingConnection();
    skt->write("READY\n");
    skt->waitForReadyRead(5000);
    qDebug() << skt->readAll();
    skt->write("OK\n");
    skt->waitForBytesWritten();
    skt->close();
    skt->deleteLater();
  }
}

<强>的main.cpp

#include "server.hpp"

int main(int argc, char** argv)
{
  QCoreApplication app(argc, argv);
  Server srv;
  return app.exec();
}