如何在 QML ApplicationWindow 中获取 activeFocusControl 的类名

How to get the className of activeFocusControl in QML ApplicationWindow

我试试

ApplicationWindow {
    onActiveFocusControlChanged: {
    console.log(activeFocusControl)
    console.log(activeFocusControl.objectName)
    }
}

输出:

qml: QQuickTextField(0xa6ec00)    //the 'activeFocusControl'
qml:                              //the 'activeFocusControl.objectName'
qml: QQuickButton(0xd7ccb0)
qml:

我要

onActiveFocusControlChanged: {
    if (activeFocusControl.className == "QQuickTextField") {
        //do something
    }
    else if (activeFocusControl.className == "QQuickButton") {
        //do something
    }

但是"className"方法不存在 那我该怎么做呢?

对不起,我的英语不太好,谢谢

没有从 qml 访问 className 的方法,所以一个可能的解决方案是从 c ++ 创建一个 helper,如下所示:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <QObject>

class Helper : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE QString getClassName(QObject *obj) const{
           return obj? obj->metaObject()->className(): "";
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    Helper helper;

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("helper", &helper);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

然后在QML端使用:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button {
        id: button
        x: 270
        y: 47
        text: qsTr("Button")
    }

    TextField {
        id: textField
        x: 220
        y: 169
        text: qsTr("Text Field")
    }

    onActiveFocusControlChanged:  {
        var className = helper.getClassName(activeFocusControl)
        switch(className){
        case "QQuickTextField":
            console.log("I am QQuickTextField")
            break
        case "QQuickButton":
            console.log("I am QQuickButton")
            break
        default:
            console.log("empty")
        }
    }
}

完整的例子可以在下面link.

找到