Learn Python PyQt

PyQt button example (Python GUI)

QAbstractButton acts as an abstract class and provides the general functionality of a button, push button and checkable button. Selectable button implementations are QRadioButton and QCheckBox; pressable button implementations are QPushButton and QToolButton.

Any kind of button can be displayed with text (.setText() method set text) and icon (.setIcon() set icon) label.

Book: Create Desktop Apps with Python PyQt5

QAbstractButton

Status provided by QAbstractButton.

1、isDown() prompt whether to press
2、isChecked() prompts whether button has marked
3、isEnable() prompt whether the button can be clicked by the user
4、isCheckAble() prompt whether the button is markable
5、setAutoRepeat() sets whether the button can be repeated automatically when the user long presses the button.

The signal provided by QAbstractButton.

1、Pressed(), when the mouse is on the button and click the left button, the trigger signal
2、released(),trigger signal when the left mouse button is released
3、clicked(), when the mouse is first pressed and then released, or when the shortcut key is released to trigger the signal
4、Toggled(), trigger signal when the marker state of the button is changed

Each of the buttons will be presented next.

QPushButton :

class QPushButton(QAbstractButton)
 |  QPushButton(QWidget parent=None)
 |  QPushButton(str, QWidget parent=None)
 |  QPushButton(QIcon, str, QWidget parent=None)

This shows that QPushButton is inherited from QAbstractButton and is a command button. Click to execute some commands, or respond to some questions. Common buttons such as “Confirm”, “Apply”, “Cancel”, “Close”, “Yes”, “No”, etc.

Command Button often describes the actions performed through text. Sometimes we also use shortcuts to execute commands corresponding to buttons.

Illustrate this with an example of QPushButton.

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import sys

class PushButton(QWidget):
    def __init__(self):
        super(PushButton,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("PushButton")
        self.setGeometry(400,400,300,260)
        self.closeButton = QPushButton(self)
        self.closeButton.setText("Close")          #text
        self.closeButton.setIcon(QIcon("close.png")) #icon
        self.closeButton.setShortcut('Ctrl+D')  #shortcut key
        self.closeButton.clicked.connect(self.close)
        self.closeButton.setToolTip("Close the widget") #Tool tip
        self.closeButton.move(100,100)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = PushButton()
    ex.show()
    sys.exit(app.exec_()) 

Illustrative examples

python pyqt qpushbutton

Click on the Buttton named “Close” to close the window. The window can also be closed by pressing the shortcut “Ctrl+C”.

Code analysis.

The text and image are set with:

self.closeButton.setText("Close") #text
self.closeButton.setIcon(QIcon("close.png")) #icon
  • setText() method, set button text
  • setIcon() method, set the icon of the button

The display of button text and icons can also be set directly by the QPushButton constructor with arguments when creating an object instance.

| QPushButton(str, QWidget parent=None)
| QPushButton(QIcon, str, QWidget parent=None)

self.closeButton.setShortcut('Ctrl+D') #shortcut key

Set the shortcut method for closeButton, i.e. Ctrl+D to do the same function as clicking closeButton.

Book: Create Desktop Apps with Python PyQt5

QToolButton.

class QToolButton(QAbstractButton)
 | QToolButton(QWidget parent=None)

QToolButton is a tool action related button, usually used with QToolBar, QToolButton usually does not display text, but the icon QIcon.
An example of the QToolButton is illustrated by.

from PyQt5.QtWidgets import QApplication, QWidget, QToolButton, QMainWindow
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import sys

class ToolButton(QMainWindow):

    def __init__(self):
        super(ToolButton,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("ToolButton")
        self.setGeometry(400,400,300,260)

        self.toolbar = self.addToolBar("toolBar")
        self.statusBar()
      
        self._detailsbutton = QToolButton()                                     
        self._detailsbutton.setCheckable(True)                                  
        self._detailsbutton.setChecked(False)                                   
        self._detailsbutton.setArrowType(Qt.RightArrow)
        self._detailsbutton.setAutoRaise(True)
        #self._detailsbutton.setIcon(QIcon("test.jpg"))
        self._detailsbutton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self._detailsbutton.clicked.connect(self.showDetail)
        self.toolbar.addWidget(self._detailsbutton)

    def showDetail(self):
        if self._detailsbutton.isChecked():
            self.statusBar().showMessage("Show Detail....")
        else:
            self.statusBar().showMessage("Close Detail....")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ToolButton()
    ex.show()
    sys.exit(app.exec_()) 

Illustrative example:

pyqt toolbutton

The icon is the Buttton with the “right arrow icon” and this button has a switch. When Button is opened, “Show Detail…” is displayed in the message bar, and “Close Detail” is displayed on the reverse side.

Code analysis.

self._detailsbutton.setCheckable(True) self._detailsbutton.setChecked(False)
  • SetCheckable() method, “True” sets the button as an optional property and has both “On” and “Off” states.

  • The setChecked() method sets the state of the button to the selected state.

    self._detailsbutton.setArrowType(Qt.RightArrow)

  • The setArrowType() method sets the type of arrow displayed on the button. arrowType, arrow property, whether the button shows an arrow instead of the normal icon

  • Qt.NoArrow 0

  • Qt.UpArrow 1

  • Qt. DownArrow 2

  • Qt.LeftArrow 3

  • Qt.RightArrow 4

    self._detailsbutton.setToolButtonStyle(Qt.ToolButtonIconOnly)

setToolButtonStyle(), sets the style of the button text and icon display. The parameter in the program is to display only the icon and not the text (Qt.ToolButtonIconOnly)

The types of parameters are as follows.

  • Qt.ToolButtonIconOnly 0 Only display the icon.
  • Qt.ToolButtonTextOnly 1 Only display the text.
  • Qt.ToolButtonTextBesideIcon 2 The text appears beside the icon.
  • Qt.ToolButtonTextUnderIcon 3 The text appears under the icon.
  • Qt.ToolButtonFollowStyle 4

If you need to display both a custom icon and text during the actual use, you can set it according to the following parameters.

self._detailsbutton.setIcon(QIcon("test.jpg"))
self._detailsbutton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

Book: Create Desktop Apps with Python PyQt5