This is the second lesson in Python PyQt5, in this lesson we want tp learn about Python PyQt5 QPushButton. the QPushButton widget provides a command button. The push button, or command button, is perhaps the most commonly used widget in any graphical user interface. Push (click) a button to command the computer to perform some action, or to answer a question. Typical buttons are OK, Apply, Cancel, Close, Yes, No and Help.
First of all we need to add our imports, basically we can use QPushButton class for creating of Button in PyQt5.
1 2 3 |
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton import sys from PyQt5.QtGui import QIcon |
Using this code we can set the geometry for the window. you need to add the x, position of the window, width and height of the window.
1 |
self.setGeometry(200,200,400,300) |
For setting the window title you need to use this line of code.
1 |
self.setWindowTitle("Button - Geekscoders.com") |
If you want to add an icon in your window, you can use this code, make sure that you have already added an icon in your working directory.
1 |
self.setWindowIcon(QIcon("python.png")) |
So you can create pyqt5 buttons by creating the object of QPushButton.
1 |
btn1 = QPushButton("Click One", self) |
Sometimes you need to set the width and height of the QPushButton, you can use this code.
1 |
btn1.setGeometry(100,100, 100,100) |
If you want to set an icon for the Python PyQt5 QPushButton than you do it like this.
1 |
btn1.setIcon(QIcon("cpp.png")) |
This is the complete source code for PyQt5 How to Create QPushButton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from PyQt5.QtWidgets import QApplication,QWidget, QPushButton import sys from PyQt5.QtGui import QIcon class Window(QWidget): def __init__(self): super().__init__() self.setGeometry(200,200, 400,300) self.setWindowTitle("Button - Geekscoders.com") self.setWindowIcon(QIcon('python.png')) self.create_buttons() #self.show() def create_buttons(self): btn1 = QPushButton("Click Me", self) #btn1.setText("Our Second Text") #btn1.move(200,200) btn1.setGeometry(100,100, 100,100) btn1.setIcon(QIcon("cpp.png")) btn1.setStyleSheet('color:red') btn1.setStyleSheet('background-color:green') btn2 = QPushButton("Click Two", self) btn2.setGeometry(200,100, 100,100) btn2.setIcon(QIcon("pythonicon.png")) btn2.setStyleSheet('color:yellow') btn2.setStyleSheet('background-color:purple') app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) |
Run the complete code and this is will be the result.