简体   繁体   English

在 QLineEdit 对象 PyQt5 上设置验证器

[英]Setting a validator on a QLineEdit object PyQt5

So I'm struggling to find a solution that will point me in the right direction to set a validator on a QLineEdit to only accept floats within a defined range.因此,我正在努力寻找一种解决方案,该解决方案将为我指明正确的方向,将 QLineEdit 上的验证器设置为仅接受定义范围内的浮点数。 I've seen some examples out there but I think I'm getting tripped up on the syntax.我看过一些例子,但我想我被语法绊倒了。 Still very new to this so not very knowledgeable and not quite sure what I'm doing yet.对此仍然很陌生,所以不是很了解,也不太确定我在做什么。

So I have a program I'm working on where the GUI elements has been created with Qt Designer, and I've been using Python to create all the moving parts interacting /calling the ui elements from the compiled main.ui file after it's been converted to Python.所以我有一个程序,我正在使用 Qt Designer 创建 GUI 元素,并且我一直在使用 Python 创建所有移动部件,这些部件在编译后的 main.ui 文件中交互/调用 ui 元素。转换为 Python。 So far, I've been calling these objects using ui.(the object name).(some function/signal).到目前为止,我一直在使用 ui.(对象名称)调用这些对象。(一些函数/信号)。

So let's say I want to set a validator for one of these QLineEdit objects that I've named "lineEditSHStart".因此,假设我想为我命名为“lineEditSHStart”的这些 QLineEdit 对象之一设置验证器。 Usually ui.lineEditSHStart.(some function) has worked for me, but I'm not having any luck with getting a validator to work with this way.通常 ui.lineEditSHStart.(some function) 对我有用,但我没有运气让验证器以这种方式工作。

How would you go about doing this?你会怎么做呢? From the examples I've seen so far, this has been done through creating the elements from scratch in Python so the syntax of "self.setValidator(QDoubleValidator(9999.00, -9999.00, 2))" has been used.从我目前看到的例子来看,这是通过在 Python 中从头开始创建元素来完成的,因此使用了“self.setValidator(QDoubleValidator(9999.00, -9999.00, 2))”的语法。 I haven't seen anything working with the situation I have so far.到目前为止,我还没有看到任何适用于我的情况的东西。

Any help would be greatly appreciated!任何帮助将不胜感激!

Snip from the compiled file从编译的文件中截取

 # -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1517, 905)
        Form.setMinimumSize(QtCore.QSize(1050, 905))
        Form.setMaximumSize(QtCore.QSize(2000, 905))
        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(30, 10, 1001, 431))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(True)
        font.setWeight(75)
        self.groupBox.setFont(font)
        self.groupBox.setObjectName("groupBox")
        self.groupBoxBT = QtWidgets.QGroupBox(self.groupBox)
        self.groupBoxBT.setGeometry(QtCore.QRect(20, 40, 271, 341))
        self.groupBoxBT.setObjectName("groupBoxBT")
        self.comboBoxBT1 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT1.setGeometry(QtCore.QRect(20, 60, 121, 22))
        self.comboBoxBT1.setCurrentText("")
        self.comboBoxBT1.setObjectName("comboBoxBT1")
        self.comboBoxBT2 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT2.setGeometry(QtCore.QRect(20, 100, 121, 22))
        self.comboBoxBT2.setObjectName("comboBoxBT2")
        self.comboBoxBT3 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT3.setGeometry(QtCore.QRect(20, 140, 121, 22))
        self.comboBoxBT3.setObjectName("comboBoxBT3")
        self.comboBoxBT4 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT4.setGeometry(QtCore.QRect(20, 180, 121, 22))
        self.comboBoxBT4.setObjectName("comboBoxBT4")
        self.comboBoxBT5 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT5.setGeometry(QtCore.QRect(20, 220, 121, 22))
        self.comboBoxBT5.setObjectName("comboBoxBT5")
        self.comboBoxBT6 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT6.setGeometry(QtCore.QRect(20, 260, 121, 22))
        self.comboBoxBT6.setObjectName("comboBoxBT6")
        self.labelBTType = QtWidgets.QLabel(self.groupBoxBT)
        self.labelBTType.setGeometry(QtCore.QRect(60, 30, 47, 21))
        font = QtGui.QFont()
        font.setBold(False)
        font.setWeight(50)
        self.labelBTType.setFont(font)
        self.labelBTType.setObjectName("labelBTType")
        self.comboBoxBT7 = QtWidgets.QComboBox(self.groupBoxBT)
        self.comboBoxBT7.setGeometry(QtCore.QRect(20, 300, 121, 22))
        self.comboBoxBT7.setObjectName("comboBoxBT7")
        self.lineEditBT1 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT1.setGeometry(QtCore.QRect(180, 60, 51, 20))
        self.lineEditBT1.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.lineEditBT1.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT1.setText("")
        self.lineEditBT1.setCursorPosition(0)
        self.lineEditBT1.setPlaceholderText("")
        self.lineEditBT1.setClearButtonEnabled(True)
        self.lineEditBT1.setObjectName("lineEditBT1")
        self.lineEditBT2 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT2.setGeometry(QtCore.QRect(180, 100, 51, 20))
        self.lineEditBT2.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT2.setPlaceholderText("")
        self.lineEditBT2.setClearButtonEnabled(True)
        self.lineEditBT2.setObjectName("lineEditBT2")
        self.lineEditBT3 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT3.setGeometry(QtCore.QRect(180, 140, 51, 20))
        self.lineEditBT3.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT3.setPlaceholderText("")
        self.lineEditBT3.setClearButtonEnabled(True)
        self.lineEditBT3.setObjectName("lineEditBT3")
        self.lineEditBT4 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT4.setGeometry(QtCore.QRect(180, 180, 51, 20))
        self.lineEditBT4.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT4.setPlaceholderText("")
        self.lineEditBT4.setClearButtonEnabled(True)
        self.lineEditBT4.setObjectName("lineEditBT4")
        self.lineEditBT5 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT5.setGeometry(QtCore.QRect(180, 220, 51, 20))
        self.lineEditBT5.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT5.setPlaceholderText("")
        self.lineEditBT5.setClearButtonEnabled(True)
        self.lineEditBT5.setObjectName("lineEditBT5")
        self.lineEditBT6 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT6.setGeometry(QtCore.QRect(180, 260, 51, 20))
        self.lineEditBT6.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT6.setPlaceholderText("")
        self.lineEditBT6.setClearButtonEnabled(True)
        self.lineEditBT6.setObjectName("lineEditBT6")
        self.lineEditBT7 = QtWidgets.QLineEdit(self.groupBoxBT)
        self.lineEditBT7.setGeometry(QtCore.QRect(180, 300, 51, 20))
        self.lineEditBT7.setInputMethodHints(QtCore.Qt.ImhNone)
        self.lineEditBT7.setPlaceholderText("")
        self.lineEditBT7.setClearButtonEnabled(True)
        self.lineEditBT7.setObjectName("lineEditBT7")
        self.labelBTQuanity = QtWidgets.QLabel(self.groupBoxBT)
        self.labelBTQuanity.setGeometry(QtCore.QRect(170, 30, 81, 21))

main.py主文件

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
import gui_main
import numpy as np 



#==========================================
# create app and main window + dialog GUI
# =========================================

app = QApplication(sys.argv)



window = QWidget()
ui = gui_main.Ui_Form()
ui.setupUi(window)


#========================================
# GUI event handler and related functions
# =======================================

def calcTotalDynamicHead():        # Define function to compute all calculations based off user input variables when "calculate" button is pressed
    
    # Creating a dictionary of key/value pairs from the items chosen from the combo boxes and their corresponding quanities 
    btList = {ui.comboBoxBT1.currentText() : ui.lineEditBT1.text(), ui.comboBoxBT2.currentText() : ui.lineEditBT2.text(), ui.comboBoxBT3.currentText() : ui.lineEditBT3.text(), ui.comboBoxBT4.currentText() : ui.lineEditBT4.text(), ui.comboBoxBT5.currentText() : ui.lineEditBT5.text(), ui.comboBoxBT6.currentText() : ui.lineEditBT6.text(), ui.comboBoxBT7.currentText() : ui.lineEditBT7.text()}
    
    # Creating a dictionary of variable pairs of item types and their straight length conversion factors
    conversionBT = {'Standard Tee':'5.7133', 'Through Tee': '1.7893', 'Standard Elbow': '2.6701', 'Medium Sweep Elbow': '2.258', 'Long Sweep Elbow': '1.7893', '45 Degree Bend': '1.2308'}
    
    # Creating a dictionary of variable pairs from the items chosen from the combo boxes and their corresponding quanities
    valveList = {ui.comboBoxV1.currentText() : ui.lineEditV1.text(), ui.comboBoxV2.currentText() : ui.lineEditV2.text(), ui.comboBoxV3.currentText() : ui.lineEditV3.text(), ui.comboBoxV4.currentText() : ui.lineEditV4.text(), ui.comboBoxV5.currentText() : ui.lineEditV5.text(), ui.comboBoxV6.currentText() : ui.lineEditV6.text(), ui.comboBoxV7.currentText() : ui.lineEditV7.text() }
    
    # Creating a dictionary of variable pairs of item types and their straight length conversion factors
    conversionValve = {'Globe Valve' : '28.716', 'Swing Check Valve' : '6.7493', 'Gate Valve Open' : '0.5668', 'Gate Valve 3/4 Closed' : '71.126', 'Gate Valve 1/2 Closed' : '16.971', 'Gate Valve 1/4 Closed' : '3.3958', 'Plug Valve': '7.179'}
    
    # Grabbing all necessary variables from ui elements for calculations and error handling
    totalStraightPipe = ui.lineEditPipeLen.text()
    pipeDia = ui.lineEditDia.text()
    startEle = ui.lineEditSHStart.text()
    endEle = ui.lineEditSHEnd.text()
    highPt = ui.lineEditSHHigh.text()
    targetFlow = ui.lineEditFHTarget.text()
    minFlow = ui.lineEditFHMin.text()
    maxFlow = ui.lineEditFHMax.text()
    kVal = ui.lineEditFHKvalue.text()
    cFactor = ui.lineEditFHCfac.text()
    minVel = ui.spinBoxFHVelMin.value()  
    maxVel = ui.spinBoxFHVelMax.value() 
    
    # Creating empty lists and dictionaries for storing calculated values
    btCalcs = []
    valveCalcs = []
    calcFlows = {}
    

    try: 
        # Loop through the Bends and Tees combo boxes and look for selections in order to convert items to their straight length equivalents 
        for item in btList:
            
            if item != '' :
                
                quanity = btList[item]
                
                eqLenPerFit = float(conversionBT[item]) * int(pipeDia)
        
                totalEqLen = float(eqLenPerFit) * float(quanity)
                
                btCalcs.append(totalEqLen)
              
            else:
                
                pass
        
        # Loop through the Valve combo boxes and look for selections in order to covert items to their straight length equivalents
        for item in valveList:
            
            if item != '':
                
                quanity = valveList[item]
                
                eqLenPerValve = float(conversionValve[item]) * int(pipeDia)
                
                totalEqLen = float(eqLenPerValve) * float(quanity)
                
                valveCalcs.append(totalEqLen)
                
            else:
                
                pass
            
        # Sum all the converted straight length values appended to the Bends and Tees list
        totalBt = sum(map(float,btCalcs))
        
        # Sum all the converted straight length values appened to the Valves list
        totalValves = sum(map(float, valveCalcs))
        
        # Calculate the total equivalnet length for all Bends and Tees, Valves, and Straight Pipe Segment
        totalEqLength = totalBt + totalValves + float(totalStraightPipe)
        
        # Calculate the Static Head 
        if endEle < highPt:
            staticHead = float(highPt) - float(startEle)
        else:
            staticHead = float(endEle) - float(startEle)
        
        # Create a list of defined flow rates from the user input Min and Max Flows in order to perform calculations for each flow rate
        flowList = np.arange(int(minFlow),int(maxFlow)+1, 100)
        
        # Loop through the defined flow ranges and calculate the Head Loss per 100ft, Velocity, Velocity Head, Friction Head, and Total Dynamic Head for each flow rate
        for flow in flowList:
           
            # Create an empty dictionary with each flow rate as a key and an empty list for storing corresponding calculated values. Plan on expanding in the future and will be nice to have all this info in a nice callable place
            calcFlows.update({flow: []})
            
            # Calculate Head Loss per 100ft
            headLoss = 2.083 * (100/int(cFactor))**1.85 * (int(flow)**1.85/int(pipeDia)**4.8655)
            
            # Calculate velocity
            velocity = (int(flow)/448.8)/(3.14159*(int(pipeDia)/24)**2)
            
            # Calculate Velocity Head
            velocityHead = int(velocity)**2 / 64.4
            
            # Calculate Friction Head
            frictionHead = int(totalEqLength) * (headLoss/1000) + (velocityHead * int(kVal))
            
            # Calculate Total Dynamic Head
            totalDynamicHead = float(staticHead) + float(frictionHead)
            
            # Append each calculation to it's corresponding flow key in the dictionary 
            calcFlows[flow].append(headLoss)
            calcFlows[flow].append(velocity)
            calcFlows[flow].append(velocityHead)
            calcFlows[flow].append(frictionHead)
            calcFlows[flow].append(totalDynamicHead)
    
        # Update all the corresponding ui elements with their calculated value
        ui.lineEditTotalEqLen.setText("{:.2f} ft".format(totalEqLength))
        ui.lineEditStaticHead.setText("{:.2f} ft".format(staticHead))
        ui.lineEditFHHeadLoss.setText("{:.2f} ft".format(calcFlows[int(targetFlow)][0]))
        ui.lineEditFHVelocity.setText("{:.2f} ft/sec".format(calcFlows[int(targetFlow)][1]))
        ui.lineEditFHVelHead.setText("{:.2f} v**2/(2g)".format(calcFlows[int(targetFlow)][2]))
        ui.lineEditFHFrictionHead.setText("{:.2f} ft".format(calcFlows[int(targetFlow)][3]))
        ui.lineEditTotalDynHead.setText("{:.2f} ft".format(calcFlows[int(targetFlow)][4]))
        
        # Checking if the calculated velocity falls within the user defined range, turns the lineEdit object green/red
        if int(minVel) < calcFlows[int(targetFlow)][1] < int(maxVel):
            ui.lineEditFHVelocity.setStyleSheet("background-color: rgb(0, 170, 0);")
        else:
            ui.lineEditFHVelocity.setStyleSheet("background-color: rgb(255, 0, 0);")
        
        # plots all calculated total dynamic head values per flow rates into graph 
        x = flowList
        y = [calcFlows[key][-1] for key in calcFlows.keys()] 
        ui.graphWidget.plot(x,y, name = targetFlow, symbol='o', symbolSize=10)
    

    # Error handling / Checks for any empty lineEdit(s) and notifies user through a dialog box and hightlights corresponding box red 
    except:
        
        if pipeDia == '':
            ui.lineEditDia.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Pipe Diameter", QMessageBox.Ok)
        elif totalStraightPipe == '':
            ui.lineEditPipeLen.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Straight Pipe Segment Length", QMessageBox.Ok)
        elif startEle == '.':
            ui.lineEditSHStart.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Starting Elevation", QMessageBox.Ok)
        elif endEle == '.':
            ui.lineEditSHEnd.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Ending Elevation", QMessageBox.Ok)
        elif targetFlow == '':
            ui.lineEditFHTarget.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Target Flow", QMessageBox.Ok)
        elif minFlow == '':
            ui.lineEditFHMin.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Minimum Flow", QMessageBox.Ok)
        elif maxFlow == '':
            ui.lineEditFHMax.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing Maximum Flow", QMessageBox.Ok)
        elif kVal  == '':
            ui.lineEditFHKvalue.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing K Value", QMessageBox.Ok)
        elif cFactor  == '':
            ui.lineEditFHCfac.setStyleSheet("background-color: rgb(255, 0, 0);")
            QMessageBox.information(window,"Information", "Missing C Factor Value", QMessageBox.Ok)
            
            
# Event handling functions for returning lineEdit object backgrounds to white after a missing value has been entered      
def resetlineEditDia():
    ui.lineEditDia.setStyleSheet("background-color: rgb(255,255,255);")

def resetlineEditPipeLen():
    ui.lineEditPipeLen.setStyleSheet("background-color: rgb(255,255,255);") 

def resetlineEditSHStart():
    ui.lineEditSHStart.setStyleSheet("background-color: rgb(255,255,255);")
    
def resetlineEditSHEnd():
    ui.lineEditSHEnd.setStyleSheet("background-color: rgb(255,255,255);")
    
def resetlineEditFHTarget():
     ui.lineEditFHTarget.setStyleSheet("background-color: rgb(255,255,255);")
     
def resetlineEditFHMin():
    ui.lineEditFHMin.setStyleSheet("background-color: rgb(255,255,255);")
    
def resetlineEditFHMax():
    ui.lineEditFHMax.setStyleSheet("background-color: rgb(255,255,255);")

def resetlineEditFHKvalue():
    ui.lineEditFHKvalue.setStyleSheet("background-color: rgb(255,255,255);")

def resetlineEditFHCfac():
    ui.lineEditFHCfac.setStyleSheet("background-color: rgb(255,255,255);")    


#==========================================
# connect signals
#==========================================
    
# Connecting button press to calculate function
ui.calcTotalDynHeadBt.clicked.connect(calcTotalDynamicHead)

# Connecting text change signals to background resets
ui.lineEditDia.textChanged.connect(resetlineEditDia)
ui.lineEditPipeLen.textChanged.connect(resetlineEditPipeLen)
ui.lineEditSHStart.textChanged.connect(resetlineEditSHStart)
ui.lineEditSHEnd.textChanged.connect(resetlineEditSHEnd)
ui.lineEditFHTarget.textChanged.connect(resetlineEditFHTarget)
ui.lineEditFHMin.textChanged.connect(resetlineEditFHMin)
ui.lineEditFHMax.textChanged.connect(resetlineEditFHMax)
ui.lineEditFHKvalue.textChanged.connect(resetlineEditFHKvalue)
ui.lineEditFHCfac.textChanged.connect(resetlineEditFHCfac)



# Bends and Tees Combo Box Options
ui.comboBoxBT1.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])
ui.comboBoxBT2.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])
ui.comboBoxBT3.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])
ui.comboBoxBT4.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])
ui.comboBoxBT5.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])
ui.comboBoxBT6.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])
ui.comboBoxBT7.addItems(['', 'Standard Tee', 'Through Tee', 'Standard Elbow', 'Medium Sweep Elbow', 'Long Sweep Elbow', '45 Degree Bend'])

# Valves Combo Box Options
ui.comboBoxV1.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV2.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV3.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV4.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV5.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV6.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV6.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])
ui.comboBoxV7.addItems(['', 'Globe Valve', 'Swing Check Valve', 'Gate Valve Open', 'Gate Valve 3/4 Closed', 'Gate Valve 1/2 Closed', 'Gate Valve 1/4 Closed', 'Plug Valve'])

# Graph styling
ui.graphWidget.setTitle("STORAGE FEED SYSTEM CURVE", color="k", size="18pt")
ui.graphWidget.setBackground('w')
ui.graphWidget.setLabel("left", "TDH (FT)", color="k", size="16pt")
ui.graphWidget.setLabel("bottom", "Flow Rate (GPM per pump)", color="k", size="16pt")
ui.graphWidget.showGrid(x=True, y=True)
ui.graphWidget.addLegend()

#=======================================
# run app
#=======================================
window.show()
sys.exit(app.exec_())

Convert ui file to python file python -m PyQt5.uic.pyuic -x untitled.ui -o window.py将ui文件转换为python文件python -m PyQt5.uic.pyuic -x untitled.ui -o window.py

untitled.ui无题.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <widget class="QLineEdit" name="lineEditSHStart"/>
   </item>
   <item>
    <widget class="QPushButton" name="action_button">
     <property name="text">
      <string>PushButton</string>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

main.py主文件

from PyQt5 import QtWidgets, QtCore, QtGui
import sys

import window  # Import convert .ui file.


class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.ui = window.Ui_Form()
        self.ui.setupUi(self)

        validator = QtGui.QDoubleValidator()  # Create validator.
        validator.setRange( -10.0, 9999.0, 2)
        self.ui.lineEditSHStart.setValidator(validator)  # Set validator.
 

if __name__ == '__main__':
    
    app = QtWidgets.QApplication(sys.argv)
    win = Window()
    win.show()
    app.exec_()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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