pyqt5 button

In this tutorial you’ll learn how to add button widgets to an existing Pyqt window and how to connect a click to a Python method. The button widget is called QPushButton.

If you do not have PyQt installed, see the previous tutorial.

Related course

pyqt5 button example

Start by importing QPushButton

from PyQt5.QtWidgets import QPushButton

In the window constructor, add these lines

pybutton = QPushButton('Click me', self)
pybutton.resize(100,32)
pybutton.move(50, 50)        
pybutton.clicked.connect(self.clickMethod)

The first line creates an object of the type QPushButton.

We resize it to 100 pixels in width and 32 in height. Then we set it to position (50,50) on the window.
The click must be linked to a Python method, clickMethod().

The end program will look like this:

pyqt button
Pyqt button widgets, QPushButton

Complete code resulting in:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize    
     
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(300, 200))    
        self.setWindowTitle("PyQt button example - pythonprogramminglanguage.com") 
        
        pybutton = QPushButton('Click me', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(100,32)
        pybutton.move(50, 50)        
    
    def clickMethod(self):
        print('Clicked Pyqt button.')

    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

 


pyqt5 message box
pyqt5 center window

Leave a Reply

Your email address will not be published. Required fields are marked *