因此,我正在努力找到一个解决方案,为我指明正确的方向,在QLineEdit上设置一个验证器,只接受定义范围内的浮动。我已经看到了一些例子,但是我想我在语法上被绊倒了。还是很新,所以不是很有知识,也不太确定我在做什么
因此,我有一个正在开发的程序,其中GUI元素是使用Qt Designer创建的,我一直在使用Python在编译的main.ui文件转换为Python后,创建所有与ui元素交互/调用的移动部件。到目前为止,我一直在使用ui调用这些对象。(对象名称)。(一些函数/信号)
假设我想为我命名为“lineEditSHStart”的QLineEdit对象之一设置一个验证器。通常ui.lineEditsStart.(一些函数)对我来说是有效的,但我没有任何运气让验证器以这种方式工作
你打算怎么做?从我到目前为止看到的示例来看,这是通过在Python中从头创建元素来实现的,因此使用了“self.setValidator(QDoubleValidator(9999.00,-9999.00,2))的语法。到目前为止,我还没有看到任何与我的处境有关的东西
任何帮助都将不胜感激
从编译后的文件中剪切
# -*- 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_())
将ui文件转换为python文件
python -m PyQt5.uic.pyuic -x untitled.ui -o window.py
无标题的.ui
main.py
相关问题 更多 >
编程相关推荐