简体   繁体   中英

How to sub class the QLineEdit in PyQt5?

My intention, to make Make all my QLineEdit with SetClearButtonEnabled,setTextmargin, and my text become a title validator (the First character of each Word become a Capital). So try to SubClass the QLineEdit. But it does not work. How to make corrections and work perfectly?

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_())

The objective of subclassifying is to modify an existing method, in your case add a method that does not exist which does not seem logical. For the first 2 methods it can be invoked directly in the constructor and for the last one use a 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM