QML ListView + TextInput 焦点

3

我有一个相当简单的QML示例:

import QtQuick 2.10
import QtQuick.Controls 2.1
import QtQuick.Window 2.10

Window {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button {
        id: but
        text: "press"
        onPressed: {
            profileModel.insertRow(list.count)
            list.currentIndex = list.count-1
            list.currentItem.focus = true
            list.currentItem.text = "focused " + list.currentIndex
            //list.currentItem.cursorVisible = true
        }
    }

    ListView {
        id: list
        anchors.top: but.bottom
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.right: parent.right

        model: profileModel
        delegate: TextInput {
            text: display
            //activeFocusOnPress: true

            onFocusChanged: {
                console.log("onFocusChanged " + index + ", " + focus)
            }
            onEditingFinished: {
                console.log("onEditingFinished " + index + ", " + focus)
            }
        }
    }
}

profileModel 的定义如下:

ProfileModel::ProfileModel(QObject *parent)
    : QAbstractListModel(parent)
    , m_count(3)
{

}

QVariant ProfileModel::data(const QModelIndex &index, int role) const
{
    return index.row();
}

Qt::ItemFlags ProfileModel::flags(const QModelIndex &index) const
{
    return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
}

bool ProfileModel::insertRows(int position, int rows, const QModelIndex &index)
{
    beginInsertRows(QModelIndex(), position, position + rows - 1);
    m_count++;
    endInsertRows();
    return true;
}

bool ProfileModel::removeRows(int position, int rows, const QModelIndex &index)
{
    return QAbstractListModel::removeRows(position, rows, index);
}

int ProfileModel::rowCount(const QModelIndex &parent) const
{
    return m_count;
}

bool ProfileModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    return true;
}

无论我做什么,都无法在按下按钮后将焦点聚集到 TextInput 上。 从日志中看,一切似乎是正确的,即在按下按钮后,我看到我失去了先前项目的焦点,并获得了新创建项目的焦点,但也仅如此。
D/libuntitled.so( 6871): qrc:/main.qml:38 (onFocusChanged): qml: onFocusChanged 3, true
D/libuntitled.so( 6871): qrc:/main.qml:38 (onFocusChanged): qml: onFocusChanged 0, false

如果我想编辑一行(或者移动光标),我必须点击它。可以使用Qt.inputMethod.show()强制显示键盘或者使用cursorVisible = true显示光标,但是输入框仍然无法激活。我使用的是Qt 5.10.0版本。
1个回答

2

我太不耐烦了。 这个答案 详细介绍了何时调用哪个与焦点相关的函数。简而言之,我必须调用 forceActiveFocus() 而不仅仅是设置 focus = true


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接