Skip to content

[PySide] How to Make a Button

Last Updated on 2021-11-08 by Clay

No matter any component we want to make, the button is the most important and basic one.

In Qt framework, we can use very easy way to make a button. Today I want to record of it with code.

(Note: The PySide version is PySide6)


Sample Code

The program below is rewritten from official document.

@slot() is a decorator. Decorator is a Python syntactic sugar. Since I haven’t written a similar note-taking article, so I recommend you can search the more information on the Internet.

# coding: utf-8
import sys
from PySide6.QtWidgets import QApplication, QPushButton
from PySide6.QtCore import Slot


@Slot()
def hello_world():
    print("Hello World!")


def main():
    app = QApplication([])
    button = QPushButton("Click")
    button.clicked.connect(hello_world)
    button.show()
    app.exec()


if __name__ == "__main__":
    main()



Output:

Click the Click button in the center, the terminal will print out:

Hello World!

Explanation

QPushButton is the Qt button component, we need to make the button event via the following code:

button.clicked.connect(hello_world)


Then we can trigger hello_world() function when we click the button; Yes, no parentheses are required.

The above is the most basic example of buttons in PySide6.


References


References

Leave a Reply