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

Is it possible to connect a signal to a static slot without a receiver instance?

本文关键字:信号 情况下 连接 插槽 静态 实例 接收器 是否      更新时间:2023-10-16

是否可以在没有接收器实例的情况下将信号连接到静态插槽?

像这样: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是对的,在这种情况下最好使用singleton模式,但我仍然很惊讶为什么这个功能还没有实现。

更新:

在Qt 5中,这是可能的。

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();

编辑:

连接对象的唯一接口是功能

bool QObject::connect ( const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method, Qt::ConnectionType type = Qt::AutoConnection )

你打算如何摆脱const QObject * receiver

检查项目中的moc文件,它会自动说话。

确实如此。(使用Qt5)

#include <QApplication>
#include <QDebug>
void foo(){
    qDebug() << "focusChanged";
}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    QObject::connect(&app, &QApplication::focusChanged, foo);
    return app.exec();
}

在Qt的早期版本中,虽然你不能像@UmNyobe提到的那样这样做,但如果你真的想调用静态插槽,你可以这样做:

connect(&object, SIGNAL(some()), this, SLOT(foo()));
void foo()
{
    .... //call your static function here.
}