连接到派生类中的受保护插槽

时间:2015-05-02 11:09:39

标签: c++ qt qt5 signals-slots

这是基类中声明的外观:

protected:
    void indexAll();
    void cleanAll();

在派生类中,以下内容无法编译:

indexAll();  // OK
connect(&_timer, &QTimer::timeout, this, &FileIndex::indexAll);  // ERROR
connect(&_timer, SIGNAL(timeout()), this, SLOT(indexAll()));  // OK

我想使用connect的第一个变体,因为它会进行一些编译时检查。为什么会返回错误:

error: 'void Files::FileIndex::indexAll()' is protected
void FileIndex::indexAll()
      ^
[...].cpp:246:58: error: within this context
     connect(&_timer, &QTimer::timeout, this, &FileIndex::indexAll);
                                                          ^

1 个答案:

答案 0 :(得分:0)

第一个由普通的C ++可访问性规则决定。 QTimer :: timeout信号直接通过提供的函数指针调用FileIndex :: indexAll。当然,这只有在这个函数指针是公共的时才可能(忽略可能的朋友解决方案)。如果使用函数指针,甚至不需要在头文件中将函数标记为SLOT。

第二个是moc magic。通过元对象系统调用。我从来没有深入研究这个话题......它只是奏效了。 : - )

好的,不是最好的解释。如果您想了解更多信息:

http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html

http://woboq.com/blog/how-qt-signals-slots-work.html

http://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html

好读,但......如果您对Qt的更深层运作感兴趣,那么......如果你想自己开发Qt,恕我直言。