美文网首页
【PySide2学习笔记】3_简单的QDialog应用

【PySide2学习笔记】3_简单的QDialog应用

作者: 4thirteen2one | 来源:发表于2019-04-22 20:10 被阅读0次

1. stub代码

所谓 stub code 桩代码,就是占坑的代码,桩代码给出的实现是临时性的/待编辑的。
它使得程序在结构上能够符合标准,又能够使程序员可以暂时不编辑这段代码。(此处参考什么是桩代码(Stub)? - nipan的回答 - 知乎

import sys
from PySide2.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton

# a simple stub that creates and shows a dialog
# This stub is updated during the course of this tutorial, 
# but you can use this stub as is if you need to

# class that subclasses PySide2 widgets
# subclassing QDialog to define a custom dialog
class Form(QDialog):

    def __init__(self, parent=None):
        # calls the QDialog’s init method with the parent widget
        super(Form, self).__init__(parent)
        #  sets the title of the dialog window
        self.setWindowTitle("My Form")

if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)

    # Create and show the form
    form = Form()
    form.show()
    
    # Run the main Qt loop
    sys.exit(app.exec_())

# build a simple dialog with some basic widgets
# let users provide their name in a QLineEdit, 
# and the dialog greets them on click of a QPushButton

2. Dialog

import sys
from PySide2.QtWidgets import (QLineEdit, QPushButton, QApplication,
    QVBoxLayout, QDialog)

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        # Create widgets
        self.edit = QLineEdit("Write my name here")
        self.button = QPushButton("Show Greetings")

        # Create layout and add widgets
        layout = QVBoxLayout()                          # lay out the widgets vertically
        layout.addWidget(self.edit)
        layout.addWidget(self.button)

        # Set dialog layout
        self.setLayout(layout)

        # Add button signal to greetings slot
        # connect the QPushButton to the Form.greetings() method
        self.button.clicked.connect(self.greetings)

    # Greets the user
    def greetings(self):
        print ("Hello %s" % self.edit.text())

if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)
    # Create and show the form
    form = Form()
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())

运行结果如下:


Dialog.png

相关文章

网友评论

      本文标题:【PySide2学习笔记】3_简单的QDialog应用

      本文链接:https://www.haomeiwen.com/subject/mynugqtx.html