問題描述
是否可以在沒有接收器實例的情況下將信號連接到靜態插槽?
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.
這篇關于是否可以在沒有接收器實例的情況下將信號連接到靜態插槽?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!