pyqt5視窗呼叫
阿新 • • 發佈:2018-12-18
我使用 uic
模組直接讀取 ui 檔案.
好處:
- 一個ui對應一個py檔案
- 直接修改ui, 然後執行py檔案即可
不好的地方在於, ui裡面的資訊在編輯的時候不會有提示.
- 建立兩個ui檔案:
main.ui
和testDialog.ui
testDialog.py
import sys
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi
class testDialog(QDialog):
def __init__(self):
super(testDialog, self).__init__()
loadUi('testDialog.ui', self)
self.bt_1.clicked.connect(self.changeText)
self.show()
def changeText(self):
self.bt_1.setText('你點選了我')
main.py
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class main(QMainWindow):
def __init__(self):
super(main, self).__init__()
loadUi('main.ui', self)
self.bt_showTestDialog.clicked.connect(self.showTestDialog)
self.show()
def showTestDialog(self):
from testDialog import testDialog
d = testDialog()
d. exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = main()
sys.exit(app.exec_())
這樣直接執行就可以了
另外還有一個 snippets. 做完ui檔案後, 新建一個和ui同名的py檔案. 輸入gui_main / gui_dialog 自動根據檔名生成程式碼:
"Python GUI main": {
"prefix": "gui_main",
"body": [
"import sys",
"from PyQt5.QtWidgets import QApplication, QMainWindow",
"from PyQt5.uic import loadUi",
"",
"",
"class ${1:$TM_FILENAME_BASE}(QMainWindow):",
"\tdef __init__(self):",
"\t\tsuper($1, self).__init__()",
"\t\tloadUi('$1.ui', self)",
"\t\t$2",
"\t\tself.show()",
"",
"",
"if __name__ == '__main__':",
"\tapp = QApplication(sys.argv)",
"\tmain = $1()",
"\tsys.exit(app.exec_())",
],
"description": "Python GUI 自動生成 main"
},
"Python GUI dialog": {
"prefix": "gui_dialog",
"body": [
"import sys",
"from PyQt5.QtWidgets import QApplication, QDialog",
"from PyQt5.uic import loadUi",
"",
"",
"class ${1:$TM_FILENAME_BASE}(QDialog):",
"\tdef __init__(self):",
"\t\tsuper($1, self).__init__()",
"\t\tloadUi('$1.ui', self)",
"\t\t$2",
"\t\tself.show()",
"",
"",
"if __name__ == '__main__':",
"\tapp = QApplication(sys.argv)",
"\tmain = $1()",
"\tsys.exit(app.exec_())",
],
"description": "Python GUI 自動生成 dialog"
}