1 - About QPushButton class

The QPushButton widget provides a command button. The button, or command button, is perhaps the most commonly used widget in any GUI: pressing a button to command the computer to perform an action or to answer a question. Typical buttons are OK, Apply, Cancel, Close, Yes, No, and Help.

2 - Create a PyQt5 Button with the QPusButton class

To create a command button of the QPushButton type, all you have to do is instantiate the QPusButton class:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton

app = QApplication(sys.argv)
win = QWidget()
win.setGeometry(100 , 100 , 500 , 300)

# create a QPusButton
q_btn = QPushButton(win)
q_btn.setText("This is a QPusButton ! ")
q_btn.setGeometry(100 , 100 , 200 , 50)

win.show()
app.exec_()

 

3 - Bind an action to a QPushButton PyQt5 button

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton

# create a button action
def action():
print("Why you clicked the button !")

app = QApplication(sys.argv)
win = QWidget()
win.setGeometry(100 , 100 , 500 , 300)

# create a QPusButton
q_btn = QPushButton(win)
q_btn.setText("This is a QPusButton ! ")
q_btn.setGeometry(100 , 100 , 200 , 50)

# bind an action to the button
q_btn.clicked.connect(action)
win.show()
app.exec_()

4 - QPushButton PyQt5 according to the Python object approach

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton

class Window(QWidget):

def __init__(self , window):
super().__init__()
self.window = window

def action(self):
print("Why you clicked the button !")

def build(self):
self.window.setWindowTitle("Window With QPusButton !")
self.window.setGeometry(100 , 100 , 500 , 300)

# create a QPushButton
self.q_btn = QPushButton(self.window)
self.q_btn.setText("This is a QPushButton from object approach !")
self.q_btn.setGeometry(100 , 100 , 250 , 35)
self.q_btn.clicked.connect(self.action)


if __name__ == "__main__":
app = QApplication(sys.argv)
win = QWidget()

myWin = Window(win)
myWin.build()

win.show()
app.exec_()
Younes Derfoufi
my-courses.net

Leave a Reply