首页 > 解决方案 > SpinBox 中的 KeyNavigation 在 qml 中不起作用

问题描述

我在我的代码KeyNavigation.tab属性中使用以使导航在 qml 中可用。

但是控件SpinBox无法使用它。例如,如果我在它和我希望它导航的元素之间有一个控件,它不会遵守规则。

我将用一个真实的例子来说明。

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Controls 1.4
import QtQuick.Controls 2.0

ApplicationWindow {
    id: window
    title: "Stack"
    visible: true
    height: 200
    width: 400
    Item {
        id: page
        anchors.fill: parent
        width:parent.width
        height: parent.height
        ScrollView {
            id:scrollView
            anchors.fill:parent
            Column{
                width:parent.width
                spacing:10
                TextField {
                    id:textField
                    KeyNavigation.tab: spinBox1
                    implicitHeight: 30
                    font.bold: true
                }
                SpinBox {
                    id: spinBox1
                    KeyNavigation.tab: spinBox2
                    width: 100
                    height: 30
                    editable: true
                }
                ComboBox {
                    id:comboBox
                    //KeyNavigation.tab: spinBox2
                    anchors.topMargin: 10
                    textRole: "text"
                }
                SpinBox {
                    id: spinBox2
                    KeyNavigation.tab: textField
                    width: 100
                    height: 30
                    editable: true
                }
            }
        }
    }
}

如果我们使用制表符,这里spinBox1不会跳转。spinBox2

这是在 Windows 10 操作系统上测试的

使用的 Qt 版本是 5.11.1

标签: qtqml

解决方案


出于某种原因,如果附加属性设置在 SpinBox 本身而不是其 TextInput 上,则不会调用 QQuickKeyNavigationAttached::keyPressed()。因此,使用 contentItem 上的附加属性是一种解决方法:

    SpinBox {
        Component.onCompleted: contentItem.KeyNavigation.tab = spinBox
    }

推荐阅读