問題描述
是否可以在沒有接收器實(shí)例的情況下將信號(hào)連接到靜態(tài)插槽?
Is it possible to connect a signal to static slot without receiver instance?
像這樣:connect(&object, SIGNAL(some()), STATIC_SLOT(staticFooMember()));
Qt 文檔中有一個(gè)帶有 [static slot] 屬性的 QApplication::closeAllWindows()
函數(shù).文檔中有一個(gè)使用它的示例:
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()));
是否允許執(zhí)行相同的操作但不傳遞實(shí)例變量(例如,當(dāng)一個(gè)類只有靜態(tài)函數(shù)時(shí))?
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();
};
<小時(shí)>
也許 Frank Osterfeld 是對(duì)的,在這種情況下最好使用單例模式,但我仍然很驚訝為什么這個(gè)功能還沒有實(shí)現(xiàn).
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 中你不能:
不,這是不允許的.相反,允許使用作為靜態(tài)函數(shù)的插槽,但為了能夠連接它,您需要一個(gè)實(shí)例.
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();
連接對(duì)象的唯一接口是函數(shù)
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
?
檢查項(xiàng)目中的 moc
文件,它會(huì)自己說話.
Check the moc
files in your project, it speaks by itself.
這篇關(guān)于是否可以在沒有接收器實(shí)例的情況下將信號(hào)連接到靜態(tài)插槽?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!