如何在 PyQt5 中子 class QLineEdit?

How to sub class the QLineEdit in PyQt5?

我的意图是使用 SetClearButtonEnabled、setTextmargin 制作我所有的 QLineEdit,并且我的文本成为标题验证器(每个单词的第一个字符成为大写字母)。所以尝试对 QLineEdit 进行子类化。但它不起作用。如何修正并完美运行?

import sys
from PyQt5.QtWidgets import QWidget,QVBoxLayout,QLineEdit,QApplication
from PyQt5.QtCore import Qt,pyqtSignal

class My_QLineedit(QLineEdit):
    def mytext(self,text):
        self.text.setClearButtonEnabled(True)
        self.text.setTextMargins(5, 5, 5, 5)
        self.text.title()


class MsgBox(QWidget) :

    def __init__(self):
        super().__init__()
        self.tb1 = QLineEdit("tb1")
        self.tb1.setClearButtonEnabled(True)
        self.tb1.setTextMargins(5,5,5,5)
        self.tb1.setObjectName("textbox_1")

        self.tb2 = My_QLineedit(self)
        self.tb2.setObjectName("textbox_2")

        self.tb3 = My_QLineedit()
        self.tb3.setObjectName("textbox_3")

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.tb1)
        self.vbox.addWidget(self.tb2)
        self.vbox.addWidget(self.tb3)
        self.setLayout(self.vbox)
        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainwindow = MsgBox()
    mainwindow.show()
    sys.exit(app.exec_())

子类化的objective是修改已有的方法,你的情况是添加一个不存在的方法,看起来不合逻辑。对于前 2 个方法,它可以在构造函数中直接调用,对于最后一个方法,使用 QValidator:

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


class My_QLineedit(QLineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setClearButtonEnabled(True)
        self.setTextMargins(5, 5, 5, 5)
        self.setValidator(TitleValidator())