pyqt5窗口调用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xiao2752271456/article/details/83623896

我使用 uic 模块直接读取 ui 文件.
好处:

  • 一个ui对应一个py文件
  • 直接修改ui, 然后运行py文件即可

不好的地方在于, ui里面的信息在编辑的时候不会有提示.

  1. 创建两个ui文件: main.uitestDialog.ui
    在这里插入图片描述
    在这里插入图片描述
  2. 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('你点击了我')
  1. 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"
	}
展开阅读全文

没有更多推荐了,返回首页