亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 QRegExpValidator 總是返回 2

為什么 QRegExpValidator 總是返回 2

智慧大石 2023-06-06 16:15:07
我QRegExpValidator一直認為我的輸入是Acceptable- 它不應該是。在 gui.py 中有一個QLineEdit名為`from gui import Ui_Dialogfrom PyQt5.QtWidgets import QDialog, QApplicationfrom PyQt5 import QtCorefrom PyQt5.QtGui import QRegExpValidatorfrom PyQt5.QtCore import QRegExpimport sysclass AppWindow(QDialog):? ?? ? def __init__(self):? ? ? ? super().__init__()? ? ? ? self.ui = Ui_Dialog()? ? ? ? self.ui.setupUi(self)? ? ? ? self.show()? ? ? ? self.ui.number.textChanged[str].connect(self.validate_number)? ? def validate_number(self):? ? ? ? regex = QRegExp("^[0-9]{3}$")? ? ? ? tmp = QRegExpValidator(regex, self.ui.number)? ? ? ? print(tmp.Acceptable)if __name__ == "__main__":? ? app = QApplication(sys.argv)? ? w = AppWindow()? ? w.show()? ? sys.exit(app.exec_())2無論我嘗試什么,輸出總是如此。我希望我輸入任何內容,如果它是 3 位數字,則該函數返回 True(或可接受)。
查看完整描述

1 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

OP 似乎不了解 QValidator 如何與 QLineEdit 一起工作。


邏輯是 QValidator 使用方法 setValidator 設置為 QLineEdit,其中已經建立連接,以便每次更改 QLineEdit 的文本時,調用“validate”方法,返回狀態、新位置和新文本(如果需要更正)。


class AppWindow(QDialog):   

    def __init__(self):

        super().__init__()

        self.ui = Ui_Dialog()

        self.ui.setupUi(self)

        self.show()


        regex = QRegExp("^[0-9]{3}$")

        validator = QRegExpValidator(regex, self.ui.number)

        self.ui.number.setValidator(validator)

另一方面,由于“tmp”是一個 QValidator,那么 tmp.Acceptable 等同于 QValidator.Acceptable,當打印它時,會獲得該枚舉的數值。


如果你想分析驗證器狀態的值,那么你有以下選項:


覆蓋驗證(最推薦):


class RegExpValidator(QRegExpValidator):

    def validate(self, text, position):

        state, new_text, new_position = super().validate(text, position)

        print(state)

        return state, new_text, new_position



class AppWindow(QDialog):   

    def __init__(self):

        super().__init__()

        self.ui = Ui_Dialog()

        self.ui.setupUi(self)

        self.show()


        regex = QRegExp("^[0-9]{3}$")

        validator = RegExpValidator(regex, self.ui.number)

        self.ui.number.setValidator(validator)

調用驗證方法:


class AppWindow(QDialog):

    def __init__(self):

        super().__init__()

        self.ui = Ui_Dialog()

        self.ui.setupUi(self)

        self.show()


        self.ui.number.textChanged[str].connect(self.validate_number)


    def validate_number(self):

        regex = QRegExp("^[0-9]{3}$")

        tmp = QRegExpValidator(regex, self.ui.number)

        state, new_text, new_position = tmp.validate(

            self.ui.number.text(), self.ui.number.cursorPosition()

        )

        print(state)


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號