在QLineEdit中是否具有title()?

问题描述 投票:4回答:1

在我的程序中。使用两个QLineEdit。第一个是正常,第二个是titled line edit。第一个/正常的QLineEidt可以正常工作,但是在第二个文本框(QLineEdit)中,我无法插入文本在乞讨时或一次在任何地方。

例如:我输入了文本“ Python”。现在,我在文本的开头添加“ Hello”(“ Hello Python”)。如果我尝试键入“ Hello”,则一次只能插入一个单词,(按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()
python pyqt pyqt5 title qlineedit
1个回答
3
投票

问题是,当您使用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()
© www.soinside.com 2019 - 2024. All rights reserved.