C++ Qt 支持虚拟纯插槽吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2998216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Qt support virtual pure slots?
提问by ereOn
My GUI project in Qt
has a lot of "configuration pages" classes which all inherit directly from QWidget
.
我的 GUI 项目中Qt
有很多“配置页面”类,它们都直接从QWidget
.
Recently, I realized that all these classes share 2 commons slots (loadSettings()
and saveSettings()
).
最近,我意识到所有这些类共享 2 个公共插槽(loadSettings()
和saveSettings()
)。
Regarding this, I have two questions:
对此,我有两个问题:
- Does it make sense to write a intermediate base abstract class (lets name it
BaseConfigurationPage
) with these two slots as virtual pure methods ? (Every possible configuration page will alwayshave these two methods, so I would say "yes") - Before I do the heavy change in my code (if I have to) : does Qt support virtual pure slots ? Is there anything I should be aware of ?
BaseConfigurationPage
使用这两个插槽作为虚拟纯方法编写中间基抽象类(让我们命名)是否有意义?(每个可能的配置页面总会有这两种方法,所以我会说“是”)- 在我对代码进行重大更改之前(如果必须的话):Qt 是否支持虚拟纯插槽?有什么我应该注意的吗?
Here is a code example describing everything:
这是一个描述所有内容的代码示例:
class BaseConfigurationPage : public QWidget
{
// Some constructor and other methods, irrelevant here.
public slots:
virtual void loadSettings() = 0;
virtual void saveSettings() = 0;
};
class GeneralConfigurationPage : public BaseConfigurationPage
{
// Some constructor and other methods, irrelevant here.
public slots:
void loadSettings();
void saveSettings();
};
回答by ianmac45
Yes, just like regular c++ pure virtual methods. The code generated by MOC does call the pure virtual slots, but that's ok since the base class can't be instantiated anyway...
是的,就像常规的 C++ 纯虚方法一样。MOC 生成的代码确实调用了纯虚拟插槽,但这没关系,因为无论如何都无法实例化基类......
Again, just like regular c++ pure virtual methods, the class cannot be instantiated until the methods are given an implementation.
同样,就像常规的 c++ 纯虚方法一样,在给方法一个实现之前,不能实例化类。
One thing: in the subclass, you actuallly don't need to mark the overriden methods as slots. First, they're already implemented as slots in the base class. Second, you're just creating more work for the MOC and compiler since you're adding a (tiny) bit more code. Trivial, but whatever.
一件事:在子类中,您实际上不需要将覆盖的方法标记为插槽。首先,它们已经作为基类中的槽实现了。其次,您只是在为 MOC 和编译器创建更多工作,因为您要添加更多(微小的)代码。微不足道,但无论如何。
So, go for it..
所以,加油吧。。
回答by lygstate
Only slots in the BaseConfigurationPage
仅 BaseConfigurationPage 中的插槽
class BaseConfigurationPage : public QWidget
{
// Some constructor and other methods, irrelevant here.
public slots:
virtual void loadSettings() = 0;
virtual void saveSettings() = 0;
};
class GeneralConfigurationPage : public BaseConfigurationPage
{
// Some constructor and other methods, irrelevant here.
void loadSettings();
void saveSettings();
};