qt - 在具有不同 parents 的 class 中的 objects 之间发送信号

qt - send signal between objects in a class with different parents

我有一个class(例如"controller") 在这个 class 中,我创建了许多 object 不同的其他 classes 不同 parents.

如何在 classes 和 "controller" 之间发送信号以调用 "controller" class 中的函数?

    #include "controller.h"


    Controller::Controller(QObject *parent) : QObject (parent){
        connect(sender(), SIGNAL(recivedCall(QString)), this, SLOT(alert(QString)));
    }

    void Controller::onCall(QJsonObject callinfo){
         nodes[callinfo["username"].toString()]= new PanelManager();
         nodes[callinfo["username"].toString()]->handleCallStateChanged(callinfo);
    }

    void Controller::alert(QString callinfo){
        qDebug()<<callinfo;
    }

例如,如何在每个"PanelManager"object中从"recivedCall"发送信号来调用"controller"class中的"alert"函数?

创建两个组件的对象必须设置信号和槽之间的连接。但是,您不应该公开内部组件(即创建 getter 到 return 属性指针)。

解决 Qt 的最后一个问题的一种方法是在您的父级中创建一个信号并让它广播调用。 例如,如果我需要在两个不同的小部件中将 QCheckBox 连接到 QLineEdit:

class Parent1: public QWidget
{
    Q_OBJECT
public:
    Parent1(): QWidget(), myCheckBox(new QCheckBox("Edit", this))
    {
        connect(myCheckBox, &QCheckBox::clicked, this, &Parent1::editForbidden);
    }
private:
    QCheckBox* myCheckBox;
signals:
    void editForbidden(bool);
};


class Parent2: public QWidget
{
    Q_OBJECT
public:
    Parent2(): QWidget(), myLineEdit(new QLineEdit("Edit", this))
    {
        connect(this, &Parent2::forbidEdit, myLineEdit, &QLineEdit::setReadOnly);
    }
private:
    QLineEdit* myLineEdit;
signals:
    void forbidEdit(bool);
};


// In the parent of Parent1 and Parent2 (or in the main if there is no parent)
QObject::connect(p1, &Parent1::editForbidden, p2, &Parent2::forbidEdit);

在此示例中,当我单击 parent1 中的复选框时,parent2 中的 lineEdit 被禁用。但是,Parent1对Parent2一无所知。