python - QLineEdit 中的 title() 问题?

标签 python pyqt pyqt5 title qlineedit

在我的程序中。使用两个 QLineEdit。第一个是正常的,第二个是标题行编辑 .第一个/普通 QLineEidt 工作顺利,但在第二个文本框(QLineEdit)中,我 无法插入文本 在乞讨或任何时间的任何地方。

例如:我输入了一个文本“Python”。现在我将“Hello”添加到文本(“Hello Python”)中。如果我尝试输入“你好”,我一次只能插入一个单词,(按home键,输入单词“H”,光标跳到最后,再次将光标移动到第二个位置并输入一个单词“O”,一旦我们输入单词“O”,光标就会跳转到文本的末尾,依此类推)。我想一次输入(插入)一个文本。

如何克服?

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont

class Lineedit_title(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100,100,500,500)

        self.textbox1 = QLineEdit(self)
        self.textbox1.setGeometry(50,50,200,50)
        self.textbox1.setFont(QFont("Caliber", 15, QFont.Bold))

        self.textbox2 = QLineEdit(self)
        self.textbox2.setGeometry(50,140,200,50)
        self.textbox2.setFont(QFont("Caliber",15,QFont.Bold))
        self.textbox2.textChanged.connect(self.textbox_textchange)

    def textbox_textchange(self,txt):
        self.textbox2.setText(txt.title())

def main():
    app = QApplication(sys.argv)
    win = Lineedit_title()
    win.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

最佳答案

问题是当你使用setText()光标位置设置在文本的末尾,在这种情况下,光标位置必须在setText()前后进行保存和恢复。 , 分别:

def textbox_textchange(self, txt):
    position = self.textbox2.cursorPosition()
    self.textbox2.setText(txt.title())
    self.textbox2.setCursorPosition(position)

更优雅的解决方案是使用自定义验证器:
import sys
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget
from PyQt5.QtGui import QFont, QValidator


class TitleValidator(QValidator):
    def validate(self, text, pos):
        return QValidator.Acceptable, text.title(), pos


class Lineedit_title(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 500, 500)

        self.textbox1 = QLineEdit(self)
        self.textbox1.setGeometry(50, 50, 200, 50)
        self.textbox1.setFont(QFont("Caliber", 15, QFont.Bold))

        self.textbox2 = QLineEdit(self)
        self.textbox2.setGeometry(50, 140, 200, 50)
        self.textbox2.setFont(QFont("Caliber", 15, QFont.Bold))

        validator = TitleValidator(self.textbox2)
        self.textbox2.setValidator(validator)


def main():
    app = QApplication(sys.argv)
    win = Lineedit_title()
    win.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

关于python - QLineEdit 中的 title() 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62120999/

相关文章:

python - 使用 Python 解析网站

python - 如何在覆盖模式下将 Pandas 数据框保存到 csv?

python - PyQt5:使用类创建窗口

python - 在 python 3.6+ 和 PyQt5 中 pickle QPolygon

python - 如何将鼠标点击信号连接到 pyqtgraph 绘图小部件

python - 正则表达式 Python 在单个表达式中提取两个字符串之间的数字

python - 序列中的随机字符串

python - 刷新 GUI 窗口

python - 如何选择QTableWidget的多个单元格?

python - 无法使用新数据点更新 Pyqtgraph 图