Qt信号未被发射

时间:2017-07-01 19:00:27

标签: c++ qt qtcpsocket

我的QTcpSocket里面有一个QMainWindow。我需要将connected()disconnected()readyRead()信号转发给QMainWindow。只需将套接字信号连接到我的自定义类插槽,这样做非常简单。然后从我的自定义类向我的主窗口插槽发出信号,对吗?我这样做但无济于事。即使从主窗口插槽运行emit client->sendData("data")也是如此。我获得了成功的SIGNAL / SLOT连接。但是当从我的自定义类中发出这些时,我得不到任何数据传递。这是我的相关代码:

Mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    client = new Client(this);
    qDebug() << "1st success = " << connect(client, &Client::sendData, this, &MainWindow::dataReady);
    qDebug() << "2nd success = " << connect(client, &Client::clientConnected, this, &MainWindow::clientConnected);
    qDebug() << "3rd success = " << connect(client, &Client::clientDisconnected, this, &MainWindow::clientDisconnected);
    emit client->sendData("Hello!");
}

MainWindow::~MainWindow()
{

}

void MainWindow::on_pushButtonConnect_clicked()
{
    if (isConnected)
        client->disconnect();
    if (client)
        client->connectToServer(ui->lineEditServerIp->text(), ui->lineEditServerPort->text().toInt());
}

void MainWindow::on_pushButtonDisconnect_clicked()
{
    client->disconnectToServer();
}

void MainWindow::dataReady(QByteArray data)
{
    qDebug() << data;
}

void MainWindow::clientConnected()
{
    isConnected = true;
    ui->lineEditServerIp->setEnabled(false);
    ui->lineEditServerPort->setEnabled(false);
    ui->pushButtonConnect->setEnabled(false);
    ui->pushButtonDisconnect->setEnabled(true);
}

void MainWindow::clientDisconnected()
{
    isConnected = false;
    ui->lineEditServerIp->setEnabled(true);
    ui->lineEditServerPort->setEnabled(true);
    ui->pushButtonConnect->setEnabled(true);
    ui->pushButtonDisconnect->setEnabled(false);
}

MainWindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include "client.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void dataReady(QByteArray data);

    void clientConnected();

    void clientDisconnected();

private slots:

    void on_pushButtonConnect_clicked();

    void on_pushButtonDisconnect_clicked();

private:
    Ui::MainWindow *ui;
    Client *client;

    bool isConnected;
};

#endif // MAINWINDOW_H

Client.cpp:

#include "client.h"

Client::Client(QObject *parent) : QObject(parent)
{
    socket = new QTcpSocket(this);
    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconected()));
    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64)));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
}

bool Client::connectToServer(QString ipAddress, int port)
{
    if (socket && socket->state() != QAbstractSocket::ConnectedState)
    {
        qDebug() << "Now connecting to:" << ipAddress << ":" << port;

        socket->connectToHost(ipAddress, port);

        if (!socket->waitForConnected(3000))
        {
            qDebug() << "Connection error: " << socket->errorString();
            return false;
        }
        else
        {
            qDebug() << "Successfully connected!";
            return true;
        }
    }
    else if (!socket)
    {
        qDebug() << "Socket unitialized.";
        return false;
    }

    else if (socket->state() == QAbstractSocket::ConnectedState)
    {
        qDebug() << "Socket already connect to" << socket->peerName() << ".";
        return false;
    }

    return false;
}

void Client::disconnectToServer()
{
    socket->disconnectFromHost();
}

void Client::connected()
{
    qDebug() << "Successfully connected.";
    emit this->clientConnected();

}

void Client::disconected()
{
    qDebug() << "Disconnected from server.";
    emit this->clientDisconnected();
}

void Client::bytesWritten(qint64 bytes)
{
    qDebug() << bytes;
}

void Client::readyRead()
{
    QByteArray data = socket->readAll();
    qDebug() << "Server: " << data;
    emit this->sendData(data);
}

Client.h:

#ifndef CLIENT_H
#define CLIENT_H

#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>

class Client : public QObject
{
    Q_OBJECT
public:
    explicit Client(QObject *parent = nullptr);

    bool connectToServer(QString ipAddress, int port);
    void disconnectToServer();

signals:
    void sendData(QByteArray data);

    void clientConnected();

    void clientDisconnected();

public slots:
    void connected();

    void disconected();

    void bytesWritten(qint64 bytes);

    void readyRead();

private:
    QTcpSocket *socket;

};

#endif // CLIENT_H

Moc_client.cpp:

/****************************************************************************
** Meta object code from reading C++ file 'client.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "../../FLClient/client.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'client.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Client_t {
    QByteArrayData data[9];
    char stringdata0[86];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
    Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
    qptrdiff(offsetof(qt_meta_stringdata_Client_t, stringdata0) + ofs \
        - idx * sizeof(QByteArrayData)) \
    )
static const qt_meta_stringdata_Client_t qt_meta_stringdata_Client = {
    {
QT_MOC_LITERAL(0, 0, 6), // "Client"
QT_MOC_LITERAL(1, 7, 8), // "sendData"
QT_MOC_LITERAL(2, 16, 0), // ""
QT_MOC_LITERAL(3, 17, 4), // "data"
QT_MOC_LITERAL(4, 22, 15), // "clientConnected"
QT_MOC_LITERAL(5, 38, 18), // "clientDisconnected"
QT_MOC_LITERAL(6, 57, 12), // "bytesWritten"
QT_MOC_LITERAL(7, 70, 5), // "bytes"
QT_MOC_LITERAL(8, 76, 9) // "readyRead"

    },
    "Client\0sendData\0\0data\0clientConnected\0"
    "clientDisconnected\0bytesWritten\0bytes\0"
    "readyRead"
};
#undef QT_MOC_LITERAL

static const uint qt_meta_data_Client[] = {

 // content:
       7,       // revision
       0,       // classname
       0,    0, // classinfo
       5,   14, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       3,       // signalCount

 // signals: name, argc, parameters, tag, flags
       1,    1,   39,    2, 0x06 /* Public */,
       4,    0,   42,    2, 0x06 /* Public */,
       5,    0,   43,    2, 0x06 /* Public */,

 // slots: name, argc, parameters, tag, flags
       6,    1,   44,    2, 0x0a /* Public */,
       8,    0,   47,    2, 0x0a /* Public */,

 // signals: parameters
    QMetaType::Void, QMetaType::QByteArray,    3,
    QMetaType::Void,
    QMetaType::Void,

 // slots: parameters
    QMetaType::Void, QMetaType::LongLong,    7,
    QMetaType::Void,

       0        // eod
};

void Client::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        Client *_t = static_cast<Client *>(_o);
        Q_UNUSED(_t)
        switch (_id) {
        case 0: _t->sendData((*reinterpret_cast< QByteArray(*)>(_a[1]))); break;
        case 1: _t->clientConnected(); break;
        case 2: _t->clientDisconnected(); break;
        case 3: _t->bytesWritten((*reinterpret_cast< qint64(*)>(_a[1]))); break;
        case 4: _t->readyRead(); break;
        default: ;
        }
    } else if (_c == QMetaObject::IndexOfMethod) {
        int *result = reinterpret_cast<int *>(_a[0]);
        void **func = reinterpret_cast<void **>(_a[1]);
        {
            typedef void (Client::*_t)(QByteArray );
            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Client::sendData)) {
                *result = 0;
                return;
            }
        }
        {
            typedef void (Client::*_t)();
            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Client::clientConnected)) {
                *result = 1;
                return;
            }
        }
        {
            typedef void (Client::*_t)();
            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Client::clientDisconnected)) {
                *result = 2;
                return;
            }
        }
    }
}

const QMetaObject Client::staticMetaObject = {
    { &QObject::staticMetaObject, qt_meta_stringdata_Client.data,
      qt_meta_data_Client,  qt_static_metacall, nullptr, nullptr}
};


const QMetaObject *Client::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}

void *Client::qt_metacast(const char *_clname)
{
    if (!_clname) return nullptr;
    if (!strcmp(_clname, qt_meta_stringdata_Client.stringdata0))
        return static_cast<void*>(const_cast< Client*>(this));
    return QObject::qt_metacast(_clname);
}

int Client::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 5)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 5;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 5)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 5;
    }
    return _id;
}

// SIGNAL 0
void Client::sendData(QByteArray _t1)
{
    void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
    QMetaObject::activate(this, &staticMetaObject, 0, _a);
}

// SIGNAL 1
void Client::clientConnected()
{
    QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}

// SIGNAL 2
void Client::clientDisconnected()
{
    QMetaObject::activate(this, &staticMetaObject, 2, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE

0 个答案:

没有答案