PYQT5界面类继承以及软件功能开发小记
首先使用代码将QT designer制作的.ui文件转代码
import os
# 指定 .ui 文件所在目录
ui_dir = './UI'
# 列出目录下所有 .ui 文件
def list_ui_files():return [f for f in os.listdir(ui_dir) if f.endswith('.ui')]
# 将 .ui 文件转换为 .py 文件
def convert_ui_to_py():ui_files = list_ui_files()for ui_file in ui_files:py_file = os.path.splitext(ui_file)[0] + '.py'cmd = f'pyuic5 -o {py_file} {ui_dir}/{ui_file}'os.system(cmd)print(f"已转换: {ui_file} -> {py_file}")
if __name__ == "__main__":convert_ui_to_py()
转换后得到UI界面的大类,
class Ui_Form(object):def setupUi(self, Form):Form.setObjectName("Form")Form.resize(502, 264)icon = QtGui.QIcon()icon.addPixmap(QtGui.QPixmap("./UI\\favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)Form.setWindowIcon(icon)Form.setStyleSheet("")self.lineEdit = QtWidgets.QLineEdit(Form)self.lineEdit.setGeometry(QtCore.QRect(210, 30, 81, 20))self.lineEdit.setObjectName("lineEdit")self.lineEdit_2 = QtWidgets.QLineEdit(Form)self.lineEdit_2.setGeometry(QtCore.QRect(310, 30, 81, 20))self.lineEdit_2.setObjectName("lineEdit_2")self.label = QtWidgets.QLabel(Form)self.label.setGeometry(QtCore.QRect(60, 30, 121, 21))font = QtGui.QFont()font.setFamily("黑体")font.setPointSize(14)self.label.setFont(font)self.label.setTextFormat(QtCore.Qt.AutoText)self.label.setObjectName("label")self.label_2 = QtWidgets.QLabel(Form)self.label_2.setGeometry(QtCore.QRect(10, 90, 191, 21))font = QtGui.QFont()font.setFamily("黑体")font.setPointSize(14)self.label_2.setFont(font)self.label_2.setTextFormat(QtCore.Qt.AutoText)self.label_2.setObjectName("label_2")self.lineEdit_3 = QtWidgets.QLineEdit(Form)self.lineEdit_3.setGeometry(QtCore.QRect(220, 90, 61, 20))self.lineEdit_3.setObjectName("lineEdit_3")self.lineEdit_4 = QtWidgets.QLineEdit(Form)self.lineEdit_4.setGeometry(QtCore.QRect(320, 90, 61, 20))self.lineEdit_4.setObjectName("lineEdit_4")self.label_3 = QtWidgets.QLabel(Form)self.label_3.setGeometry(QtCore.QRect(290, 90, 21, 16))font = QtGui.QFont()font.setFamily("Agency FB")font.setPointSize(10)self.label_3.setFont(font)self.label_3.setObjectName("label_3")self.label_4 = QtWidgets.QLabel(Form)self.label_4.setGeometry(QtCore.QRect(390, 90, 21, 16))font = QtGui.QFont()font.setFamily("Agency FB")font.setPointSize(10)self.label_4.setFont(font)self.label_4.setObjectName("label_4")self.label_5 = QtWidgets.QLabel(Form)self.label_5.setGeometry(QtCore.QRect(480, 90, 21, 16))font = QtGui.QFont()font.setFamily("Agency FB")font.setPointSize(10)self.label_5.setFont(font)self.label_5.setObjectName("label_5")self.lineEdit_5 = QtWidgets.QLineEdit(Form)self.lineEdit_5.setGeometry(QtCore.QRect(410, 90, 61, 20))self.lineEdit_5.setObjectName("lineEdit_5")self.label_6 = QtWidgets.QLabel(Form)self.label_6.setGeometry(QtCore.QRect(40, 160, 121, 21))font = QtGui.QFont()font.setFamily("黑体")font.setPointSize(14)self.label_6.setFont(font)self.label_6.setTextFormat(QtCore.Qt.AutoText)self.label_6.setObjectName("label_6")self.lineEdit_6 = QtWidgets.QLineEdit(Form)self.lineEdit_6.setGeometry(QtCore.QRect(230, 160, 50, 20))self.lineEdit_6.setObjectName("lineEdit_6")self.lineEdit_7 = QtWidgets.QLineEdit(Form)self.lineEdit_7.setGeometry(QtCore.QRect(370, 160, 50, 20))self.lineEdit_7.setObjectName("lineEdit_7")self.pushButton = QtWidgets.QPushButton(Form)self.pushButton.setGeometry(QtCore.QRect(190, 220, 111, 23))self.pushButton.setObjectName("pushButton")self.label_7 = QtWidgets.QLabel(Form)self.label_7.setGeometry(QtCore.QRect(180, 160, 41, 20))self.label_7.setObjectName("label_7")self.label_8 = QtWidgets.QLabel(Form)self.label_8.setGeometry(QtCore.QRect(320, 160, 41, 20))self.label_8.setObjectName("label_8")self.retranslateUi(Form)QtCore.QMetaObject.connectSlotsByName(Form)def retranslateUi(self, Form):_translate = QtCore.QCoreApplication.translateForm.setWindowTitle(_translate("Form", "测回计算器YKV3.0"))self.label.setText(_translate("Form", "输入水平距离"))self.label_2.setText(_translate("Form", "各测回归零方向平均值"))self.label_3.setText(_translate("Form", "度"))self.label_4.setText(_translate("Form", "分"))self.label_5.setText(_translate("Form", "秒"))self.label_6.setText(_translate("Form", "输入2C值范围"))self.pushButton.setText(_translate("Form", "开始计算"))self.label_7.setText(_translate("Form", "最小值"))self.label_8.setText(_translate("Form", "最大值"))
在使用过程中,创建功能类MyApplication,选择QtWidgets.QWidget继承,对初始化部分代码进行修改,导入UI大类进行初始化
from Main_Window import Ui_Form
初始化时,用self.ui = Ui_Form()进行实例化,用self.ui.setupUi(self)进行UI设置,增加其他业务逻辑代码,并增加功能函数
class MyApplication(QtWidgets.QWidget):def __init__(self):super().__init__()# 创建UI实例self.ui = Ui_Form()# 设置UI,将当前窗口作为容器self.ui.setupUi(self)# 在这里添加业务逻辑代码self.ui.pushButton.clicked.connect(self.on_button_click)filename = self.resource_path(os.path.join("icon.png"))self.setWindowIcon(QIcon(filename))
丰满内容后结果如下(注意button逻辑需要添加在初始化部分,括号中放功能函数)
class MyApplication(QtWidgets.QWidget):def __init__(self):super().__init__()# 创建UI实例self.ui = Ui_Form()# 设置UI,将当前窗口作为容器self.ui.setupUi(self)# 在这里添加业务逻辑代码self.ui.pushButton.clicked.connect(self.on_button_click)filename = self.resource_path(os.path.join("icon.png"))self.setWindowIcon(QIcon(filename))def resource_path(self, relative_path):if getattr(sys, 'frozen', False):base_path = sys._MEIPASSelse:base_path = "./"ret_path = os.path.join(base_path, relative_path)return ret_pathdef get_value(self):h1_value = self.ui.lineEdit.text()h2_value = self.ui.lineEdit_2.text()h_value = [h1_value, h2_value]d_value = self.ui.lineEdit_3.text()f_value = self.ui.lineEdit_4.text()m_value = self.ui.lineEdit_5.text()gc_value = [d_value, f_value, m_value]C_value_1 = self.ui.lineEdit_6.text()C_value_2 = self.ui.lineEdit_7.text()C_value = [C_value_1, C_value_2]return h_value, gc_value, C_valuedef closeEvent(self, event):""" 重写关闭事件,询问用户是否确认退出:cite[2]:cite[4] """reply = QMessageBox.question(self, "确认退出","您确定要退出程序吗?",QMessageBox.Yes | QMessageBox.No,QMessageBox.No)if reply == QMessageBox.Yes:event.accept() # 接受关闭事件else:event.ignore() # 忽略关闭事件def on_button_click(self):h_value, gc_value, C_value = self.get_value()c_value_f = []for i in range(len(C_value)):c_value_f.append(float(C_value[i]))C_value = generate_2C_numbers(c_value_f[0], c_value_f[1])# 水平距离l_x = float(h_value[0])l_y = float(h_value[1])sp = [l_x, l_y]gc_d = gc_value[0]gc_f = gc_value[1]gc = float(gc_value[2])c_mid = len(C_value)//2e_list_up = C_value[:c_mid]e_list_down = C_value[c_mid:]# e_list_up = [-1.5, -2.0, -3.0, 1.0]# e_list_down = [-1.8, -2.0, 3.6, -2.4]col_1 = col_8 = col_11 = ['0', gc_d, '0', gc_d, '0', gc_d, '0', gc_d]col_2 = col_5 = col_9 = col_12 = ['00', gc_f, '00', gc_f, '00', gc_f, '00', gc_f]col_4_d = str(int(gc_d) + 180)col_4 = ['180', col_4_d, '180', col_4_d, '180', col_4_d, '180', col_4_d]col_14 = ['0', gc_d]col_15 = ['00', gc_f]print('-------------参数 盘左距离---------------')p_x = generate_horizontal_distance(l_x)print('-------------参数 盘右距离---------------')p_y = generate_horizontal_distance(l_y)print('++++++++++++++盘左距离++++++++++++++')print(p_x)print('++++++++++++++盘右距离++++++++++++++')print(p_y)print('---------------参数 一测回归零方向值---------------')yc = generate_first_test_regresses(gc)print('++++++++++++++一测回归零方向值++++++++++++++')print(yc)print('---------------参数 半测回归零方向值---------------')bc_up, bc_down, re_uni = half_measured_back(yc, max_diff=1.5)print('++++++++++++++半测回归零方向值++++++++++++++')print(bc_up, bc_down)up = plate_left_right(bc_up, e_list_up)pz_up = up['x']py_up = up['y']print('---------------盘左上 盘右上---------------')print(pz_up, py_up)p_up_valid, message_up = verify_solution(bc_up, pz_up, py_up)print("验证结果:", message_up)down = plate_left_right(bc_down, e_list_down)pz_down = down['x']py_down = down['y']print('---------------盘左下 盘右下---------------')print(pz_down, py_down)p_down_valid, message_down = verify_solution(bc_down, pz_down, py_down)print("验证结果:", message_down)C_2_up = diff_2C(pz_up, py_up)C_2_down = diff_2C(pz_down, py_down)# 盘左pz = []for i in range(len(pz_up)):pz.append(pz_up[i])pz.append(pz_down[i])# 盘右py = []for i in range(len(py_up)):py.append(py_up[i])py.append(py_down[i])# 2CC_2 = []for i in range(len(C_2_up)):C_2.append(C_2_up[i])C_2.append(C_2_down[i])# 半测回re_bc = []for i in range(len(bc_up)):re_bc.append(bc_up[i])re_bc.append(bc_down[i])# 一测回re_yc = []for i in range(len(yc)):re_yc.append(str('00.0'))re_yc.append(yc[i])# 距离d = []for i in range(len(p_x)):d.append(p_x[i])d.append(p_y[i])mid = len(d) // 2# 盘左距离left = d[:mid]# 盘右距离right = d[mid:]gc_list = ["00.0", gc]title = ["盘左", "盘左", "盘左", "盘右", "盘右", "盘右", "2C","半测回", "半测回", "半测回", "一测回", "一测回", "一测回","各测回", "各测回", "各测回", "盘左d", "盘右d", "水平"]data = [col_1, col_2, pz, col_4, col_5, py, C_2,col_8, col_9, re_bc, col_11, col_12, re_yc,col_14, col_15, gc_list, left, right, sp]data_str = []for k, v in enumerate(data):# 转换为字符串并保留原始精度string_numbers = [str(i) for i in v]data_str.append(string_numbers)filename = get_time_name()+'.xlsx'write_xy_to_excel(data_str, title, filename)QMessageBox.information(self, "任务完成", "恭喜,计算任务已成功完成!")# 示例使用
if __name__ == "__main__":app = QtWidgets.QApplication(sys.argv)window = MyApplication()window.show()sys.exit(app.exec_())