pyqt5 button

Add a button in pyqt?

Learn how to add button widgets to an existing Pyqt window. Learn how to connect a click to a Python method.

pyqt button

Related course:

Introduction

The button widget is called QPushButton.
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().

pyqt5 button example

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_() )

Previous Post
Next Post

Leave a Reply

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