是否可以在没有接收器实例的情况下将信号连接到静态插槽
Is it possible to connect a signal to a static slot without a receiver instance?
是否可以在没有接收器实例的情况下将信号连接到静态插槽?
像这样: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.
}
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 为什么在某些情况下不写入此文件?
- 程序在没有操作系统信号的情况下在函数中的特定行挂起
- 如何在锁定互斥锁的情况下处理主线程中的信号
- 默认情况下,从工作线程发出Qt::信号会使主线程上的UI更新?
- 处理POSIX信号:如何在不使用BackTrace_symbols的情况下获取堆栈跟踪
- 如何在没有条件变量的情况下阻止线程中的操作,并在Linux中根据信号恢复操作
- 在不中断 IO 的情况下处理信号
- 是否可以在没有接收器实例的情况下将信号连接到静态插槽
- 如何在不使用信号插槽连接的情况下触发操作
- 如何在没有信号的情况下监视子进程