我有一个相当简单的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。
答案 0 :(得分:1)
我太不耐烦了。 This answer提供了何时调用与焦点相关的功能的详细信息。简而言之,我不得不拨打forceActiveFocus()
而不是仅设置focus = true
。