PyQt5 main window, click the button to pop up the dialog child windows

First created in Qt Designer in a main window and a sub-dialog window, as shown below:
Here Insert Picture Description
After the design is completed, converted into two py files, for two separate files implementation calls the child window, I read some information, basically create a new file and then implement the main window and call the child window, not what I want, so given below my implementation, to achieve a file in the main window.
First import file sub-window in the main window file, and creating a child window of the window class initialization code is as follows:

from ChildWindowTest import *

class ChildWin(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self):
        super(ChildWin, self).__init__()
        self.setupUi(self)

The constructor super () is a must, otherwise, they can call the display sub-window, can not be called child window buttons and other controls.
Then the pop-up sub-window function to achieve, and the realization of the child window function [OK] button, click-close the sub-window and the text message is displayed in the main window of the box. Codes are as follows, to achieve performance function is defined in the main window class:

# 弹出子窗口与实现【确定】按钮功能
    def showDialog(self):
        # 创建子窗口实例
        dialog = ChildWin()
        # 显示子窗口
        dialog.show()
        # 实现子窗口中的【确定】按钮功能
        def pB_OK():
            self.textEdit.setPlainText("子窗口弹出成功!")
            dialog.close()
        # 关联【确定】按钮
        dialog.pushButton.clicked.connect(pB_OK)
        dialog.exec_()

[OK] button function which I was directly defined in the inside, pro-test effective thick, and personally feel alone than re-define convenience mess! The last line of code dialog.exec_ () is essential, many sub-window will pop up automatically closed about!
Finally, in [Open] button associated with the child window, and then displays the main window, the code can be run in the last write, as follows:

# 设置【打开子窗口】按钮
self.pushButton.clicked.connect(self.showDialog)
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

This display code is intended to be used directly in the ui converted into py file, you do not need to create a separate file and the class! After running the effect is as follows:
Here Insert Picture Description
Here Insert Picture Description

Published 17 original articles · won praise 3 · Views 1805

Guess you like

Origin blog.csdn.net/weixin_43350361/article/details/104842332