gpt4 book ai didi

c++ - 如何从槽中找出是哪个信号调用了这个槽?

转载 作者:可可西里 更新时间:2023-11-01 18:25:23 25 4
gpt4 key购买 nike

我的意思是如果我有许多不同的信号连接到同一个插槽。我看到了this有疑问但看不懂the link在答案中。能举个简单的例子吗?

最佳答案

我想你可以使用这个方法: [protected] int QObject::​senderSignalIndex() const

来自 Qt 文档:

Returns the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender(). If called outside of a slot activated by a signal, -1 is returned.

For signals with default parameters, this function will always return the index with all parameters, regardless of which was used with connect(). For example, the signal destroyed(QObject *obj = 0) will have two different indexes (with and without the parameter), but this function will always return the index with a parameter. This does not apply when overloading signals with different parameters.

Warning: This function violates the object-oriented principle of modularity. However, getting access to the signal index might be useful when many signals are connected to a single slot.

Warning: The return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.

This function was introduced in Qt 4.8.

这是我为您创建的一个小示例,用于演示其工作原理:

#include <QTimer>
#include <QMetaObject>
#include <QMetaMethod>
#include <QCoreApplication>
#include <QDebug>
#include <QObject>

class Foo : public QObject
{
Q_OBJECT
public slots:
void mySlot() {
QMetaMethod metaMethod = sender()->metaObject()->method(senderSignalIndex());
qDebug() << metaMethod.name();
qDebug() << metaMethod.methodSignature();
qApp->quit();
}
};

#include "main.moc"

int main(int argc, char **argv)
{
QCoreApplication coreApplication(argc, argv);
QTimer timer;
Foo foo;
QObject::connect(&timer, &QTimer::timeout, &foo, &Foo::mySlot);
timer.setSingleShot(true);
timer.start(1000);
return coreApplication.exec();
}

主程序

TEMPLATE = app
TARGET = main
QT = core
CONFIG += c++11
SOURCES += main.cpp

构建并运行

qmake && make && ./main

输出

"timeout"
"timeout()"

关于c++ - 如何从槽中找出是哪个信号调用了这个槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com