(四)我的第二个GUI程序,实现Python程序的界面与逻辑分离

1. 在Pycharm中,新建项目SecondGUI。

2. 调用Qt设计师(Designer.exe),新设计一个窗口的ui文件(myComboBox.ui)


3.  调用PyUIC5,将myComboBox.ui文件转为myComboBox.py文件。

4. 新建my_ComboBox.py文件。该文件是实现业务逻辑。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import pyqtSlot
import os


import myComboBox

class my_ComboBox(QtWidgets.QMainWindow,myComboBox.Ui_Form):
    def __init__(self,parent=None):
        super(QtWidgets.QMainWindow,self).__init__(parent)
        self.setupUi(self)
        self.initUI()

    def initUI(self) :
        self.comboBox.addItems(self.ListDir())    #添加选项
        self.comboBox.currentTextChanged[str].connect(self._comboxChanged)    #当选项改变时调用_self.comboxChanged()

    def ListDir(self):
        filepath="."
        _dirList = []
        for dir in os.listdir(filepath):
            _dirList.append(dir)
        return _dirList

    def _comboxChanged(self,text):
        self.textBrowser.setText(text)

5. 新建主程序SecondGUI.py。

import my_ComboBox
import sys
from PyQt5.QtWidgets import *


if __name__=="__main__":
    app=QApplication(sys.argv)
    form = my_ComboBox.my_ComboBox()
    form.show()
    sys.exit(app.exec_())
小结:当要进行界面设计时,直接调用Qt设计师(Designer.exe)修改,然后用PyUIC5.exe转成py文件,不涉及业务逻辑文件。修改业务逻辑时,只需修改业务逻辑文件(my_ComboBox.py),不涉及界面设计文件。两者实现了分离。

猜你喜欢

转载自blog.csdn.net/weixin_42691768/article/details/81056775