QLineEdit 光标在 textChanged() 或 commitData() 后移动到结尾 [英] QLineEdit cursor moves to end after textChanged() or commitData()

查看:133
本文介绍了QLineEdit 光标在 textChanged() 或 commitData() 后移动到结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QTableView,其中一列使用 QLineEdit 作为其编辑器委托,其他列需要在用户键入 时动态更新QLineEdit(例如,其中一列包含在 QLineEdit 中键入的文本的长度,它应该随着用户键入而更新,而不是等待他们按 Enter 提交).

我使用了这个代码:Qt:在编辑 QTableView 项目数据时发出信号,而不是在编辑完成后发出信号? 大多数情况下有效.它将 QLineEdit textChanged() 信号连接到编辑器的 commitData() 信号.

这段代码的问题在于,当用户输入时,QLineEdit 的插入光标总是跳到最后.如果您将文本附加到行尾,那很好.但是如果用户想在行中插入或编辑文本,每输入一个字母,文本插入光标就会跳到QLineEdit的末尾.每次击键后,他们必须重新定位光标,以便在中间完成插入/编辑.

如果我禁用映射器,则光标不会跳转,因此它不是编辑器委托所固有的;只有在使用上面链接的问题中的代码时才会发生这种情况.

我查看了 QLineEdit textChanged()commitData() 的代码,但我无法弄清楚是什么导致光标跳转到QLineEdit.有任何想法吗?谢谢!

解决方案

你可以记住上一个文本光标的位置,然后像这样手动设置:

int pos = lineEdit->cursorPosition();//改变文字lineEdit->setCursorPosition(pos);

I have a QTableView with one column that uses a QLineEdit as its editor delegate, and other columns that need to update dynamically as the user types into the QLineEdit (e.g. one of the columns contains the length of the text typed in the QLineEdit and it should update as the user types, not waiting for them to hit Enter to commit).

I used this code: Qt: Signal while a QTableView item data is being edited instead of after edit is done? which mostly works. It connects the QLineEdit textChanged() signal to the editor's commitData() signal.

The problem with this code is that as the user types, the QLineEdit's insertion cursor always jumps to the end. If you are appending text to the end of the line that's fine. But if the user wants to insert or edit text in the middle of the line, every time they type one letter, the text insertion cursor jumps to the end of the QLineEdit. After each keystroke they have to reposition the cursor in order to finish the insertion/edit in the middle.

If I disable the mapper then the cursor doesn't jump, so it isn't something inherent to the editor delegate; it only happens when using the code from the question linked above.

I looked at the code for QLineEdit textChanged() and commitData() but I can't figure out what is causing the cursor to jump to the end of the QLineEdit. Any ideas? Thanks!

解决方案

You could remember last text cursor position and then set it manually like this:

int pos = lineEdit->cursorPosition();
// change text
lineEdit->setCursorPosition(pos);

这篇关于QLineEdit 光标在 textChanged() 或 commitData() 后移动到结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆