Difference between QObject::connect vs connect methods

跟風遠走 提交于 2019-11-30 17:36:18
lpapp

You call the static version in both aforementioned cases, the signature of which is as follows:

QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection) [static]

When you are not connecting inside a QObject subclass, you will need to use the scoped variant, respectively, because you will not have an object in place to call it on. Here you can see some code representing the difference.

Not scoped

class MyClass : public QObject
{
    Q_OBJECT
    public:
        MyClass(QObject *parent) : QObject(parent) {
            connect(this, SIGNAL(mySignal()), SLOT(mySlot()));
        }

    public signals:
        void mySignal();

    public slots:
        void mySlot();
};

Scoped

int main(int argc, char **argv)
{
    QCoreApplication a(argc, argv);
    MyClass myObject;
    QObject::connect(&myObject, SIGNAL(mySignal()), &myObject, SLOT(mySlot()));
    return a.exec();
}

Please note that if you are trying to do this connection within the receiver object, you could even skip the third argument for convenience (i.e. less typing) because the non-static const version will take care of this automatically as per documentation:

QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const char * method, Qt::ConnectionType type = Qt::AutoConnection) const

This function overloads connect().

Connects signal from the sender object to this object's method.

Equivalent to connect(sender, signal, this, method, type).

Every connection you make emits a signal, so duplicate connections emit two signals. You can break a connection using disconnect().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!