Qt:QObject :: connect:没有这样的插槽QObject :: processPendingDatagrams()

时间:2016-05-04 09:47:09

标签: qt

我用Qt编写了一个UDP程序,当我连接它时:             connect(socket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));

编者告诉我 没有这样的插槽

the error click here

我想知道如何解决它,谢谢!

P.S。 这是我的文件:

files

以下是我的代码:

在这里输入代码 的 udptest.cpp:

#include "udptest.h"

#include <QObject>

#include <QUdpSocket>

#include <QtNetwork>

UDPtest::UDPtest()
{
    socket = new QUdpSocket();

    port = 2016;
    socket->bind(port,QUdpSocket::ShareAddress
                                    | QUdpSocket::ReuseAddressHint);

       connect(socket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));

}

QString UDPtest::getIP() 
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list)
    {
       if(address.protocol() == QAbstractSocket::IPv4Protocol) 
            return address.toString();  
    }
       return 0;
}








void UDPtest::sendMessage(QString message) 
{
    QByteArray data;
    QDataStream out(&data,QIODevice::WriteOnly);
    QString localHostName = QHostInfo::localHostName();
    QString address = getIP();
    out <<"123"<< localHostName << address << message;
    socket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);

}



void UDPtest::processPendingDatagrams() 
{qDebug()<<"receive";
    while(socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        socket->readDatagram(datagram.data(),datagram.size());
        QDataStream in(&datagram,QIODevice::ReadOnly);
        QString userName,localHostName,ipAddress,message;
        QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
         in >>userName >>localHostName >>ipAddress >>message;
         QString msg=time+userName+localHostName+ipAddress+message;
         msger=msg;
         qDebug()<<msg;
      }
}

QString UDPtest:: messager()
{
    return msger;
}

main.cpp中:

    #include"udptest.h"
    #include<QDebug>
    #include <QtCore/QCoreApplication>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
     qDebug()<<"123";
    UDPtest test;
    test.sendMessage("aha");
    return a.exec();
}

udptest.h:

#ifndef UDPTEST_H
#define UDPTEST_H


#include <QObject>
#include <QUdpSocket>
#include <QtCore/QCoreApplication>
#include <QtNetwork>

class UDPtest:public QObject
{

public:
    UDPtest();
    QString messager();
void sendMessage(QString);


private slots:
    void processPendingDatagrams();

private:

QString msger;
QUdpSocket *socket;
qint16 port;
QString getIP();

};

#endif // UDPTEST_H

QudptestConsole.pro:

    QT += core
QT -= gui
QT += network
CONFIG += c++11

TARGET = QudptestConsole
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp \
udptest.cpp

HEADERS += \
udptest.h

1 个答案:

答案 0 :(得分:1)

您已忘记Q_OBJECT

中的UDPtest
class UDPtest: public QObject
{
    Q_OBJECT

public:
    UDPtest();

.....
}