Is it possible to connect a signal to a static slot without a receiver instance?(是否可以在没有接收器实例的情况下将信号连接到静态插槽?)
问题描述
是否可以在没有接收器实例的情况下将信号连接到静态插槽?
Is it possible to connect a signal to static slot without receiver instance?
像这样:connect(&object, SIGNAL(some()), STATIC_SLOT(staticFooMember()));
Qt 文档中有一个带有 [static slot] 属性的 QApplication::closeAllWindows()
函数.文档中有一个使用它的示例:
There is a QApplication::closeAllWindows()
function with [static slot] attribute in Qt documentation. And there is an example of using it from the documentation:
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcuts(QKeySequence::Quit);
exitAct->setStatusTip(tr("Exit the application"));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
是否允许执行相同的操作但不传递实例变量(例如,当一个类只有静态函数时)?
Is it allowed to do the same action but without passing an instance variable (e.g. when a class has only static functions)?
class Some : public QObject {
Q_OBJECT
public slots:
static void foo();
private:
Some();
};
<小时>
也许 Frank Osterfeld 是对的,在这种情况下最好使用单例模式,但我仍然很惊讶为什么这个功能还没有实现.
Maybe Frank Osterfeld is right and it is better to use singleton pattern in this case but I am still surprised why this feature has not been implemented yet.
更新:
在 Qt 5 中这是可能的.
推荐答案
QT5 更新:是的,你可以
static void someFunction() {
qDebug() << "pressed";
}
// ... somewhere else
QObject::connect(button, &QPushButton::clicked, someFunction);
在 QT4 中你不能:
不,这是不允许的.相反,允许使用作为静态函数的插槽,但为了能够连接它,您需要一个实例.
No it is not allowed. Rather, it is allowed to use a slot which is a static function, but to be able to connect it you need an instance.
在他们的例子中,
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
意味着比他们之前所说的
means than they previously called
QApplication* qApp = QApplication::instance();
连接对象的唯一接口是函数
The only interface for connecting object is the function
bool QObject::connect ( const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method, Qt::ConnectionType type = Qt::AutoConnection )
你打算如何摆脱const QObject *receiver
?
检查项目中的 moc
文件,它会自己说话.
Check the moc
files in your project, it speaks by itself.
这篇关于是否可以在没有接收器实例的情况下将信号连接到静态插槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在没有接收器实例的情况下将信号连接
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01