是否可以在没有接收器实例的情况下将信号连接

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.

这篇关于是否可以在没有接收器实例的情况下将信号连接到静态插槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:是否可以在没有接收器实例的情况下将信号连接

基础教程推荐