This is a memorandum on how to create a QtWidget using a class.
Click here for the previously summarized article about the class https://qiita.com/kashiba/items/339b81f63612ffdba573
It's a simple window with just one button.
Every time you click the button, "Hello world" is printed.
Hello world
Hello world
Hello world
Hello world
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PySide2.QtWidgets import *
class window_A(QWidget):
def __init__(self, parent=None):
super(window, self).__init__(parent)
self.w = QWidget()
self.layout = QVBoxLayout()
#Create and place a button
self.button = QPushButton("Button")
self.layout.addWidget(self.button)
#Link button click with function hello
self.button.clicked.connect(self.hello)
self.w.setLayout(self.layout)
self.w.show()
#Called by button click
def hello(self):
print("Hello world")
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = window()
sys.exit(app.exec_())
class window_A(QWidget):
def __init__(self, parent=None):
super(window, self).__init__(parent)
Create a class window_A
that inherits QWidget and inherit init of super class (QWidget).
If you look up this area with "Class Inheritance", you will find a lot of information.
self.w = QWidget()
QVBoxLayout
Create QWidget
, which is the base of the window, and QVBoxLayout
, which is the framework for laying out the buttons. V of QVBoxLayout indicates Vertical and vertical layout, and H of QHBoxLayout indicates Horizontal and horizontal layout.
■ QVBoxLayout creation example
■ QVHoxLayout creation example
self.button = QPushButton("Button")
self.layout.addWidget(self.button)
I have created a QPushButton
object and attached the label Button
to the button.
With the ʻaddWidget command, the button is laid out at
self.layout=
QVBoxLayout`.
self.button.clicked.connect(self.hello)
I am connecting the self.hello
function to self.button
.
By using .clicked.connect
, you can connect the specified function to the event when the button is clicked. Note that we are specifying self.hello
instead ofself.hello ()
. ** () is not required. ** **
self.w.setLayout(self.layout)
self.w.show()
In .setLayout
, put self.w
= QWidget
on top of self.layout
= QVBoxLayout
.
■ Image diagram
def hello(self):
print("Hello world")
It is a function that only prints Hello world.
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = window()
sys.exit(app.exec_())
This is the process when starting a python file. After creating the QApplication, generate the window class. At the same time as the window class is generated, init will generate the window.
Click here for previously summarized articles on QApplication
andsys.exit (app.exec_ ())
https://qiita.com/kashiba/items/95f04ea9700236853803
http://tommy-on.hatenablog.com/entry/2019/04/17/231229
Recommended Posts