只有Int进入QPlainTextEdit

时间:2017-08-14 12:16:55

标签: python pyqt pyqt5

我正在python上创建一个gui,人们可以将一些数据输入到几个QPlainTextEdit元素中。我想检查一下,数据是否为Integer?如果不是 - 我需要删除所有输入的内容。我试图通过这个来做到这一点:

 regexp = QtCore.QRegExp('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$')
self.Start_i.textChanged.connect(QtGui.QRegExpValidator(regexp))

其中Start_i是QPlainTextEdit元素之一,在我看来它应该检查,输入数据是0到255之间的整数。但它不起作用。 好像我需要使用类似的东西:

if not self.Start_i.textChanged.connect(QtGui.QRegExpValidator(regexp))
self.Start_i.setPlainText(old_text[:-1])

但我不知道如何正确地做到这一点。

我也知道有QIntValidator(),尝试过这样:

 self.Start_i.textChanged.connect(QtGui.QIntValidator(0,65535))

validator = QtGui.QIntValidator(0, 100); 
self.Start_i.setValidator(validator)
UPD:我这样做了 -

self.Start_i.textChanged.connect(validation)

然后:

def validation():
    regexp = QtCore.QRegExp('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$')
    valid=QtGui.QRegExpValidator.validate(regexp)
    if not valid:
        Ui_IPG_weld.Start_i.setPlainText('0')

但得到了错误:

TypeError: validate(self, str, int): first argument of unbound method must have type 'QRegExpValidator'

UPD 2:有完整的代码:

from PyQt5 import QtGui
import re
import Ipg_weld
from Ipg_weld import Ui_IPG_weld
import Reading
import Writing


class Test(Ui_IPG_weld):
    def __init__(self):
        super().__init__()
        self.widget = QMainWindow()
        self.setupUi(self.widget)
        # ...
        self.Read_Button.clicked.connect(self.read_file)
        self.Savebutton.clicked.connect(self.write_file)
        #validator = QtGui.QIntValidator(0, 100); #Valid for values between 0 and 100
        #self.Start_i.setValidator(validator)
        self.Start_i.textChanged.connect(validation)
        self.widget.show()


    def read_file(self):
        file_values = Reading.reading()
        print("Got values from Setup_weld.src and Execute_weld.src:", file_values)
        # changing values in plainTexts
        self.Start_o.setPlainText(file_values[0][0])  #Start
        self.Strobe_o.setPlainText(file_values[0][1])  #Strobe
        self.Bit0_o.setPlainText(file_values[0][10])  #Bit0
        self.Bit1_o.setPlainText(file_values[0][9])  #Bit1
        self.Bit2_o.setPlainText(file_values[0][8])  #Bit2
        self.Bit3_o.setPlainText(file_values[0][7])  #Bit3
        self.Bit4_o.setPlainText(file_values[0][6])  #Bit4
        self.Bit5_o.setPlainText(file_values[0][5])  #Bit5
        self.Bit6_o.setPlainText(file_values[0][4])  #Bit6
        self.Bit7_o.setPlainText(file_values[0][3])  #Bit7
        self.Bit8_o.setPlainText(file_values[0][2])  #Bit8
        self.Enable_o.setPlainText(file_values[0][11])  #Enable
        self.Active_o.setPlainText(file_values[1][3]) #active
        self.Ready_o.setPlainText(file_values[1][0]) #ready
        self.Error_o.setPlainText(file_values[0][11]) #error

    def write_file(self):
       #new_values=Writing.writing()
       user_input=[]
       user_input.clear()
       user_input.append(self.Active_i.toPlainText())
       user_input.append(self.Ready_i.toPlainText())
       user_input.append(self.Error_i.toPlainText())
       user_input.append(self.Bit0_i.toPlainText())
       user_input.append(self.Bit1_i.toPlainText())
       user_input.append(self.Bit2_i.toPlainText())
       user_input.append(self.Bit3_i.toPlainText())
       user_input.append(self.Bit4_i.toPlainText())
       user_input.append(self.Bit5_i.toPlainText())
       user_input.append(self.Bit6_i.toPlainText())
       user_input.append(self.Bit7_i.toPlainText())
       user_input.append(self.Bit8_i.toPlainText())
       user_input.append(self.Strobe_i.toPlainText())
       user_input.append(self.Start_i.toPlainText())
       user_input.append(self.Enable_i.toPlainText())
       print(user_input)


def validation():
    #regexp = QtCore.QRegExp('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$')
    regexp = re.match('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$')
    valid=QtGui.QRegExpValidator.validate(regexp)
    if not valid:
     Ui_IPG_weld.Start_i.setPlainText('0')

if __name__ == '__main__':
   app = QApplication(sys.argv)
   main = Test()
   sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

第一个解决方案是实现QPlainText的keyPressEvent方法,如下所示:

class PlainTextEdit(QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        QtWidgets.QPlainTextEdit.__init__(self, parent)
        regexp = QtCore.QRegExp('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$')
        self.validator= QtGui.QRegExpValidator(regexp)

    def keyPressEvent(self, event):
        state = self.validator.validate(event.text(), 0)
        if state[0] == QtGui.QValidator.Acceptable:
            QtWidgets.QPlainTextEdit.keyPressEvent(self, event)

但是这个解决方案的缺点是它只会在用户通过键盘输入文本时才会发挥作用,但在粘贴某些文本时不会发挥作用。

因此,它实现了纠正此错误的新方法:

from PyQt5 import QtCore, QtGui, QtWidgets

class PlainTextEdit(QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        QtWidgets.QPlainTextEdit.__init__(self, parent)
        regexp = QtCore.QRegExp('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$')
        self.validator= QtGui.QRegExpValidator(regexp)
        self.document().contentsChange.connect(self.onContentsChange)

    def onContentsChange(self, position, charsRemoved, charsAdded):
        if charsAdded > 0:
            beforeText = self.toPlainText()[:position]
            text = self.toPlainText()[position:position+charsAdded]
            afterText = self.toPlainText()[position+charsAdded:]

            newText = ""

            for letter in text:
                state, _, _ = self.validator.validate(letter, 0)
                if state == QtGui.QValidator.Acceptable:
                    newText += letter

            oldState = self.document().blockSignals(True)
            self.setPlainText(beforeText+newText+afterText)
            self.document().blockSignals(oldState)

            cursor = QtGui.QTextCursor(self.document())
            cursor.movePosition(QtGui.QTextCursor.End)
            self.setTextCursor(cursor)

如果你想在Qt Designer中使用这个类,你必须为此提升它,你必须按照以下步骤:

  1. 我认为你应该拥有的项目结构如下:
  2. .
    ├── Ipg_weld.py
    ├── main.py <----Main file that you show in your question.
    └── your_designer.ui
    
    1. 您必须创建一个新的.py文件,并在其中放置我提议的PlainTextEdit类,因此结构将如下所示:
    2. .
      ├── Ipg_weld.py
      ├── main.py <----Main file that you show in your question.
      ├── PlainTextEdit.py  <-- This file has the PlainTextEdit class.
      └── your_designer.ui
      
      1. 在Qt Designer的帮助下打开.ui文件,然后单击要放置验证器的QPlainTextEdit按钮,并选择提升为... 选项:
      2. enter image description here

        1. 您将获得一个对话框窗口,如下图所示,在Promoted类名称框中,您必须放置PlainTextEdit,并且在Header File中,您必须放置PlainTextEdit.h,在按下add和Promote之后:
        2. enter image description here

          1. 在pyuic的帮助下将文件ui再次转换为文件Ipg_weld.py。
          2. 上面将加载PlainTextEdit类,你只需要运行你的主文件。