在 Qt 中,如何使用具有多重继承的 Q_OBJECT 槽和信号?
我浏览了相关问题,找不到任何能准确解决我所说的问题的内容,所以让我描述一下。
我有一个类,假设 foo 需要有自己的插槽和信号,但也需要继承 QXmlDefaultHandler (听起来很奇怪,但我在尝试使用 QHttp 将网站直接读取到 QBuffer 时遇到了这种情况)。
class foo: public QXmlDefaultHandler, public QObject
{
public:
foo();
~foo();
Q_OBJECT
public slots:
void bar();
}
如果这段代码附带一个 cpp 将 bar 连接到其他地方的信号,则将无法编译。您将收到有关 QObject 的某些成员不是 QXmlDefaultHandler 的成员的错误。此外,您不能移动 Q_OBJECT,否则您会因未实现某些功能而出现 vtable 错误(继续!尝试一下!)。
请参阅我的答案(非常简单)修复。如果我认为你解释得比我更好,我会乐意投票给你作为接受的答案。
编辑:对于你的c++和Qt老手来说,如果你能更好地解释它,请发布一个答案。我花了相当多的时间查找这些信息,所以如果你能做得比我更好,请帮助其他人。
I looked through the related questions and couldn't find anything that addresses exactly what I was talking about, so let me describe.
I have a class, let's say foo that needs to have its own slots and signals, but also needs to inherit from QXmlDefaultHandler (sounds rather odd, but I encountered this situation when trying to use QHttp to read a website directly into a QBuffer).
class foo: public QXmlDefaultHandler, public QObject
{
public:
foo();
~foo();
Q_OBJECT
public slots:
void bar();
}
This code, if accompanied by a cpp to connect bar to a signal somewhere else, will not compile. You'll get errors about some members of QObject not being a member of QXmlDefaultHandler. Additionally, you can't move Q_OBJECT or else you get vtable errors for not implementing some things (go on! try it!).
please see my answer for the (very simple) fix. I will entertain voting you as the accepted answer if I think you explain it better than I do.
edit: for you c++ and Qt vets, please post an answer if you can explain it better. i spent quite a bit of time looking this info up, so please help someone else if you can do better than me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
moc 文档指出在多重继承的情况下,提供 QObject 的类应该首先出现
The documentation for moc states that in cases of multiple inheritance, the class providing QObject should appear first
听起来很简单,如果你不把 QObject 放在继承列表的第一位,这个任务是不可能完成的。这是 Qt 元对象系统的限制。如果不这样做,编译器将尝试应用 QObject 的某些成员作为 QXmlDefaultHandler 的一部分。
As simple as it sounds, if you don't put QObject first in the inheritance list, this task is impossible. It's a limitation in Qt's meta object system. If you don't do this, the compiler will try to apply some members of QObject as part of QXmlDefaultHandler.