c++ - 是否可以对基类非 QObject 类的虚函数进行槽化

标签 c++ qt

如果我在非 QObject 基类中声明一个虚拟函数,然后将其覆盖为具有 Q_OBJECT 宏且将 QObject 作为基类之一的派生类中的插槽,它应该可以正常工作吗?

能否保证虚拟通话有效?如果连接到派生类的槽会发生什么?

class Base
{
public:
    virtual void f();
};

class Derived: public QObject, public Base
{
    Q_OBJECT
public slots:
    virtual void f();
};

最佳答案

是的:

Since slots are normal member functions, they follow the normal C++ rules when called directly. <...> You can also define slots to be virtual, which we have found quite useful in practice.

http://qt-project.org/doc/qt-4.8/signalsandslots.html#slots

在您的示例中,Derived::f 是一个普通的虚函数。如果直接调用它,它会按预期工作,就像文档中所说的那样。 signal调用时,由qt_static_metacall调用,在moc_Derived.cpp中生成如下:

void Derived::qt_static_metacall(QObject *_o, QMetaObject::Call _c, 
                                 int _id,     void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        Q_ASSERT(staticMetaObject.cast(_o));
        Derived *_t = static_cast<Derived *>(_o);
        switch (_id) {
        case 0: _t->f(); break;
        default: ;
        }
    }
    Q_UNUSED(_a);
}

因此,它以正常的函数调用 _t->f() 结束。

请注意,无法通过信号调用 Base::f。仅当当前对象实际上是 Base 实例而不是 Derived 实例时,才能执行此函数。由于 Base 不是基于 QObject 的,因此您不能将其实例传递给 connect 函数。

关于c++ - 是否可以对基类非 QObject 类的虚函数进行槽化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11023783/

相关文章:

c++ - Qt中的空文件

c++ - 如何选择从QCPCurve的哪一侧填充渐变?

c++ - 如何让 QLayouts 正确展开?

c++ - 如何在 O(1) 中从 C++ 中的 'string' 中删除终端字符?

c++ - 拒绝信号似乎只发出一次

c++ - 如何基于现有文件数据库创建具有模式的内存数据库

C++ 最佳键值容器,可按值排序并快速访问删除

c++ - 错误 : could not convert ‘((const MyClass*)this)->MyClass::myLabel’ from ‘QLabel* const’ to ‘QLabel’

Qt LGPL 许可证异常?

C++ 自定义编译时检查