jeudi 30 septembre 2021

Declare signal from interface class and implement it

I'm new to QT and I want to ask:

How can I declare signal from interface class, later implement it in another subclass and connect to slot? I found: connect(dynamic_cast<QObject*>(obj_typeof_interface), SIGNAL(signal), this, SLOT(slot)); but doesn't work...

Complete code:

My interface

class InstrumentsCommunication : public QObject
{
    Q_OBJECT
public:
    virtual bool open(const std::string addr) = 0;
    virtual void transaction(Command cmd, qint16 rate) = 0;

signals:
    virtual void getData(const QString s) = 0;

private:
    virtual void write(const std::string cmd) = 0;
};

Q_DECLARE_INTERFACE(InstrumentsCommunication, "InstrumentsCommunication")

the implementation

class SerialCommunication : public InstrumentsCommunication
{
    Q_OBJECT
    Q_INTERFACES(InstrumentsCommunication)
public:
    SerialCommunication();
    bool open(const std::string addr) override;
    void transaction(Command cmd, qint16 rate) override;

signals:
    void getData(const QString s) override;

public slots:
    void read();

private:
    QSerialPort serial;
    QString buffer;
    void write(const std::string cmd) override;
};

//Methods implementations

void SerialCommunication::read(){
    buffer += serial.readAll();

    if(buffer.contains("\r\n")){
        qDebug() << "read()";
        emit this->getData(buffer.trimmed());
        buffer = "";
    }
}

I have implemented Facory Method...

Creator class

class Creator : public QObject{
    Q_OBJECT
public:
    virtual ~Creator(){};
    virtual InstrumentsCommunication* FactoryMethod() const = 0;
    bool open(const std::string addr);
    void write(Command cmd);

signals:
    void getData(const QString s);

public slots:
    void recvData(const QString s);

private:
    InstrumentsCommunication* instrComm;
};


bool Creator::open(const std::string addr){
    instrComm = this->FactoryMethod();
    //Doesn't work
    //QObject::connect(instrComm, &InstrumentsCommunication::getData, this, &Creator::recvData);

    //Doesn't work
    //QObject::connect(dynamic_cast<QObject*>(instrComm), SIGNAL(getData), this, SLOT(recvData));

    bool isConn = instrComm->open(addr);
    return isConn;
}

//...

void Creator::recvData(const QString s){
    qDebug() << "recv";
    emit this->getData(s);
}

All declaration classes are in different .h file

Aucun commentaire:

Enregistrer un commentaire