我需要在运行时从特定 QWidget 获取可用信号列表。
例如,QWidget 是 QPushButton,我想得到这个列表:
"clicked()"
"pressed()"
"released()"
"toggled()"
"destroyed()"
...
你能给我一个提示如何做到这一点吗?谢谢
最佳答案
这是获取继承树中所有信号的代码。如果您不需要所有这些,则很容易根据您的需求进行调整:
主程序
#include <QStringList>
#include <QApplication>
#include <QPushButton>
#include <QMetaObject>
#include <QMetaMethod>
#include <QDebug>
int main(int argc, char **argv)
{
QApplication application(argc, argv);
QPushButton pushButton;
const QMetaObject* metaObject = pushButton.metaObject();
do {
for (int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) {
QMetaMethod metaMethod = metaObject->method(i);
if (metaMethod.methodType() == QMetaMethod::Signal)
qDebug() << metaMethod.methodSignature();
}
} while ((metaObject = metaObject->superClass()));
return application.exec();
}
主程序
TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp
构建和运行
qmake && make && ./main
输出
"pressed()"
"released()"
"clicked(bool)"
"clicked()"
"toggled(bool)"
"windowTitleChanged(QString)"
"windowIconChanged(QIcon)"
"windowIconTextChanged(QString)"
"customContextMenuRequested(QPoint)"
"destroyed(QObject*)"
"destroyed()"
"objectNameChanged(QString)"
关于c++ - 运行时可用信号列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27680997/