是否可以在没有接收器实例的情况下将信号连接到静态插槽?
像这样:connect(&object, SIGNAL(some()), STATIC_SLOT(staticFooMember()));
Qt 文档中有一个带有 [static slot] 属性的 QApplication::closeAllWindows()
函数。文档中有一个使用它的示例:
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcuts(QKeySequence::Quit);
exitAct->setStatusTip(tr("Exit the application"));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
是否允许在不传递实例变量的情况下执行相同的操作(例如,当一个类只有静态函数时)?
class Some : public QObject {
Q_OBJECT
public slots:
static void foo();
private:
Some();
};
也许 Frank Osterfeld 是对的,在这种情况下最好使用单例模式,但我仍然很惊讶为什么这个功能还没有实现。
更新:
最佳答案
QT5 更新:可以
static void someFunction() {
qDebug() << "pressed";
}
// ... somewhere else
QObject::connect(button, &QPushButton::clicked, someFunction);
在 QT4 中你不能:
不,这是不允许的。相反,允许使用作为静态函数的插槽,但要能够连接它,您需要一个实例。
在他们的例子中,
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
比他们以前叫的意思
QApplication* qApp = QApplication::instance();
编辑:
连接对象的唯一接口(interface)是函数
bool QObject::connect ( const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method, Qt::ConnectionType type = Qt::AutoConnection )
你打算如何摆脱 const QObject * receiver
?
检查项目中的 moc
文件,它会自己说话。
关于c++ - 是否可以在没有接收器实例的情况下将信号连接到静态插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428038/