Qt focusObjectChanged 例子?

Qt focusObjectChanged example?

我正在寻找有关如何在接收到 'focusObjectChanged' 信号时处理插槽接收到的 QObject 指针的示例。我想知道如何识别获得焦点的对象?

文档指出指针指向焦点对象,但我怎么知道是哪个?

我已经尝试在调试器中分析指针,但我没有看到任何明显的东西。

您可以确定 class 和对象名称、小部件属性...:

QObject::connect(qApp, &QApplication::focusObjectChanged, [](QObject *obj){
    if(obj) qWarning() << obj->metaObject()->className() << obj->objectName();

    QWidget* widget = qobject_cast<QWidget*>(obj);
    if(widget) qWarning() << widget->geometry(); // or other properties

    BaseType* baseType = qobject_cast<BaseType*>(obj);
    if(baseType) qWarning() << baseType->some_actions();

    Type1* type1 = qobject_cast<Type1*>(obj);
    if(Type1) qWarning() << type1->some_actions();

    Type2* type2 = qobject_cast<Type2*>(obj);
    if(Type2) qWarning() << type2->some_actions();
});

或将指针与小部件指针进行比较以找到您需要的小部件:

SomeClassSlot(QObject* obj) {
if(!obj) return;
if(obj == m_mainWindows) ....
if(obj->parent() == m_table) ...
MyClass myClass = qobject_cast<MyClass*>(obj);
if(myClass) myClass->some_method();
}