Qt“私人插槽:”这是什么?
我明白如何使用它,但它的语法让我困扰。 “私人插槽:”在做什么?
我以前从未在类定义中见过 private 关键字和 : 之间的东西。这里有一些奇特的 C++ 魔法吗?
示例如下:
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
...
I understand how to use it, but the syntax of it bothers me. What is "private slots:" doing?
I have never seen something between the private keyword and the : in a class definition before. Is there some fancy C++ magic going on here?
And example here:
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
插槽是 C++ 的 Qt 特定扩展。它仅在通过 Qt 的预处理器元对象编译器 (moc) 发送代码后进行编译。请参阅http://doc.qt.io/qt-5/moc.html 用于文档。
编辑:正如 Frank 指出的,moc 仅用于链接。额外的关键字是用标准预处理器#define 定义的。
Slots are a Qt-specific extension of C++. It only compiles after sending the code through Qt's preprocessor, the Meta-Object Compiler (moc). See http://doc.qt.io/qt-5/moc.html for documentation.
Edit: As Frank points out, moc is only required for linking. The extra keywords are #defined away with the standard preprocessor.
Qt 槽会忽略
public
、private
等关键字。所有插槽实际上都是公共的并且可以连接The keywords such as
public
,private
are ignored for Qt slots. All slots are actually public and can be connected将插槽声明为私有意味着您将无法像任何其他方法一样从它们是私有的上下文中引用它们。因此,您将无法将私有插槽地址传递给
connect
。如果您将信号声明为私有,则说明只有此类可以管理它,但 函数成员指针则不能管理它有访问限制:
除此之外,其他答案提到的内容也有效:
- 您仍然可以通过技巧从外部连接私有信号和插槽
-
signals
和slots
是空宏,不会违反语言标准Declaring slots as private means that you won't be able to reference them from context in which they are private, like any other method. Consequently you won't be able to pass private slots address to
connect
.If you declare signal as private you are saying that only this class can manage it but function member pointers do not have access restrictions:
Other than that, what other answers mention is valid too:
- you still can connect private signals and slots from outside with tricks
-
signals
andslots
are empty macros and do not break language standard如果我们要使用连接机制调用插槽,那么我们将它们声明为公共插槽。
如果我们不打算使用连接机制调用它们,那么我们就不会将它们声明为槽。
如果我们考虑以两种方式调用它们,可能是时候进行重构以适应以前的情况了。
我以前就是这么想的。
在整个 Qt 文档中,我将它们视为公开的。只要找到一个提到私人老虎机的地方
If we are going to call slots using the connect mechanism, then we declare them as public slots.
If we are not going to call them using the connect mechanism, then we do not declare them as slots.
If we are considering to call them both ways, may be its time for refactoring to fit in previous cases.
That's how I used to think.
Throughout the Qt documentation I see them as public. Just spot one place though where private slots are mentioned