使用 connect() 和 tr() 而不使用 QObject::

Use connect() and tr() without QObject::

本文关键字:QObject tr connect 使用      更新时间:2023-10-16

我经常看到人们在没有QObject::的情况下使用connect()
我该怎么做?当我只写connect()时,我收到错误:
'connect' was not declared in this scope

我不能使用using namespace QObject,因为QObject是类,而不是命名空间。

当您处于从 QObject 继承的类的成员函数中时,可以执行此操作。当您不在从QObject继承的对象范围内时,您应该使用对象实例而不是范围。

所以例如:

class MyClass : public QObject
{
    ...
    void myMemberFunction()
    {
        ...
        connect(...);  // Implicitly uses this->connect(...)
        ...
    }
    ...
};
void myNonmemberFunction(MyClass& instanceOfMyClass)
{
    ...
    instanceOfMyClass.connect(...)
    ...
}

对于翻译,您可以使用Q_DECLARE_TR_FUNCTIONS(此处的示例)。

对于连接,QObject 类定义了很多静态连接方法。