PyQt5 Quick Start PyQt5 Basic Window Components

PyQt5 Quick Start (III) PyQt5 Basic Window Components

QMainWindow

1. Brief introduction of window type

QMainWindow, QWidget and QDialog are used to create windows. They can be used directly or derivatively.
QMainWindow includes menu bar, toolbar, status bar, title bar and so on. It is the most common form of window.
QDialog is the base class of dialog window. It is mainly used to perform short-term tasks or interact with users. It can be modal or non-modal. The QDialog dialog has no menu bar, toolbar, status bar, etc.
QWidget is the base class of Qt graphics components. It can be used as a top-level window or embedded in other components.

2,QMainWindow

QMainWindow is a top-level window. QMainWindow has its own layout manager. It can not be set by setLayout. The layout is as follows:

Menu Bar is the menu bar, Toolbars is the toolbar, Dock Widgets is the docking window, Central Widget is the central window, Status Bar is the status bar.

3. QMainWindow Example

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QLabel, QDesktopWidget, QToolBar

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        # Menu Bar Settings
        self.menuBar = self.menuBar()
        self.menuBar.addAction("File")
        self.menuBar.addAction("View")

        # Toolbars
        open = QToolBar()
        open.addAction("OPen")
        self.addToolBar(open)
        close = QToolBar()
        close.addAction("Close")
        self.addToolBar(close)

        # Central Component Settings
        self.window = QWidget()
        self.setCentralWidget(self.window)

        # Status Bar Settings
        self.statusBar = self.statusBar()
        self.statusBar.showMessage("This is an status message.", 5000)
        label = QLabel("permanent status")
        self.statusBar.addPermanentWidget(label)

        self.resize(800, 600)
        self.setWindowTitle("MainWindow Demo")
        self.center()

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

QWidget

1. Introduction to QWidget

QWidget is the base class of all GUI interface components. All windows and controls inherit directly or indirectly from the base class of QWidget.

2. Window coordinate system

Qt uses a unified coordinate system to locate the position and size of window controls. The coordinate system is as follows:

The coordinate system of the screen is used to locate the top window, with the upper left corner of the screen as the origin, i.e. (0,0), the X axis from left to right and the Y axis from top to bottom. There is its own coordinate system inside the window. The coordinate system of the window takes the upper left corner as the origin, i.e. (0,0), the X axis from left to right as the positive direction, and the Y axis from top to bottom as the positive direction. The area enclosed by the origin, X axis and Y axis is the client area, and the title bar and border are around the client area.
 intx() const;
 inty() const;
 int width() const;
 int height() const;
x(), y() get the coordinates of the upper left corner of the window, but width() and height() get the width and height of the client area.
geometry().x(), geometry().y() get the upper-left coordinates of the customer area, geometry().width(), geometry().height() get the width and height of the customer area.
frameGeometry().x(), frameGeometry().y() get the upper-left coordinates of the client area, and frameGeometry().width(), frameGeometry().height() get the width and height including the client area, Title bar, border.

3. Examples of QWidget

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QDesktopWidget, QToolBar

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowTitle("MainWidget")
        self.resize(800, 600)

        self.center()

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

    def dispalyGeometry(self):
        x = self.x()
        y = self.y()
        print("x: {0}, y: {1}".format(x, y))
        x = self.pos().x()
        y = self.pos().y()
        print("x: {0}, y: {1}".format(x, y))
        x = self.frameGeometry().x()
        y = self.frameGeometry().y()
        print("x: {0}, y: {1}".format(x, y))
        x = self.geometry().x()
        y = self.geometry().y()
        print("x: {0}, y: {1}".format(x, y))
        print("geometry: ", self.geometry())
        print("frameGemetry: ", self.frameGeometry())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.show()
    window.dispalyGeometry()

    sys.exit(app.exec_())

QLabel

1. Introduction to QLabel

As a placeholder, QLabel can display non-editable text, pictures, GIF animation. QLabel is a label class of interface, inherited from QFrame.

2. Examples of QLabel

import sys
from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPalette

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = QLabel()
    window.setWindowTitle("QLabel Demo")
    window.setText("www.baidu.com")
    window.setOpenExternalLinks(True)
    pallette = QPalette()
    pallette.setColor(QPalette.Window, Qt.blue)
    window.setPalette(pallette)
    window.setAlignment(Qt.AlignCenter)
    window.setAutoFillBackground(True)
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

IV. Textbox Control

1,QLineEdit

QLineEdit is a single-line text box control that can edit a single-line string to receive user input.

import sys
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        label = QLabel("input: ", self)
        label.move(0, 0)
        lineEdit = QLineEdit(self)
        # Setting up validator
        intValidator = QIntValidator()
        lineEdit.setValidator(intValidator)
        lineEdit.setMaxLength(10)
        lineEdit.move(50, 0)
        lineEdit.textChanged.connect(self.displayText)

    def displayText(self, text):
        print(text)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

2,QTextEdit

QTextEdit is a multi-line text box editing control, which can display and edit multi-line text editing content. When the text content exceeds the display range of the control, it can display horizontal and vertical scrollbars. QTextEdit can not only display text, but also display HTML documents.

import sys
from PyQt5.QtWidgets import QApplication, QTextEdit, QWidget, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        label = QLabel("input: ", self)
        label.move(0, 0)
        self.textEdit = QTextEdit(self)
        self.textEdit.move(50, 0)

        self.textEdit.setPlainText("Hello, PyQt5")
        self.textEdit.textChanged.connect(self.displayText)

    def displayText(self):
        print(self.textEdit.toPlainText())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

5. Button Control

1,QPushButton

QPushButton inherits from QAbstractButton, which is rectangular in shape. Text and icons are displayed in rectangular areas.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button1 = QPushButton("OK", self)

        button1.clicked.connect(lambda: self.onClicked(button1))

    def onClicked(self, button):
        print("Button {0} is clicked.".format(button.text()))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

2,QRadioButton

QRadioButton inherits from QAbstractButton and provides a set of optional buttons and labels, which users can choose to display the corresponding text information. QRadioButton is a switch button that can be switched to on or off, checked or unchecked. In the radio button group, only one radio button can be selected at a time. If multiple exclusive button combinations are required, they need to be placed in the QGroupBox or QButtonGroup.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button1 = QRadioButton("OK", self)

        button1.toggled.connect(lambda: self.onClicked(button1))

    def onClicked(self, button):
        print("Button {0} is clicked.status is {1}".format(button.text(), button.isChecked()))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

3,QCheckBox

QCheckBox inherits from QAbstractButton and provides a set of checkboxes with text labels. Users can choose multiple options. Checkboxes can display text and icons.
QCheckBox has a third state besides being checked and unchecked: semi-checked, indicating no change.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button1 = QCheckBox("OK", self)

        button1.stateChanged.connect(lambda: self.onStateChanged(button1))

    def onStateChanged(self, button):
        print("Button {0} is clicked.status is {1}".format(button.text(), button.isChecked()))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

QComboBox

QComboBox is a drop-down list box.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.combo = QComboBox(self)
        self.combo.addItem("Apple")
        self.combo.addItem("HuaWei")
        self.combo.addItem("XiaoMi")
        self.combo.addItem("Oppo")

        self.combo.currentIndexChanged.connect(self.onCurrentIndex)

    def onCurrentIndex(self, index):
        print("current item is {0}".format(self.combo.currentText()))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

QSpinBox

QSpinBox is a counter control that allows the user to select an integer value, increase or decrease the value currently displayed by clicking the up or down buttons or the up or down arrows of the keyboard, and the user can also enter the current value from the edit box. By default, QSpinBox ranges from 0 to 99 with a step size of 1 for each change.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        spinBox = QSpinBox(self)

        spinBox.valueChanged.connect(self.onValueChanged)

    def onValueChanged(self, value):
        print("current value is {0}".format(value))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

QSlider

QSlider control provides a vertical or horizontal slider, which is used to control bounded values. It allows users to move the slider in a certain range along the horizontal or vertical direction, and convert the location of the slider into an integer value within a legal range.

import sys
from PyQt5.QtWidgets import QApplication, QSlider, QWidget
from PyQt5.QtCore import Qt

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        slider = QSlider(Qt.Horizontal, self)
        slider.setMaximum(20)
        slider.setMinimum(10)

        slider.valueChanged.connect(self.onValueChanged)

    def onValueChanged(self, value):
        print("current value is {0}".format(value))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

Dialog control

1,QDialog

QDialog is a dialog box class. It provides three kinds of window modes, non-modal, modal and application modes. It uses the set Windows Modality method to set window modes.
(1) Non-modal
Non-modal can interact with other windows of the application, using Qt.NonModal for settings.
(2) Window Modal
When the current dialog box is not processed, the window mode will prevent interaction with the parent window of the dialog box and set it using Qt.Modal.
(3) Application Modal
Application mode prevents any interaction with other windows, using Qt. Application Modal.
When the ESC key is pressed, the dialog window will call the QDialog.reject method by default and close the dialog box.
The setWindows Modality () method can set whether the window is a modal window or not. The default value of Qt:: Windows Modality is Qt::NonModal. If the attribute value of Qt:: Windows Modality is not set, every window displayed by the show() method is a non-modal window.
The dialog box displayed with the exec() method is a modal dialog box, which blocks the response of the window until the user closes the dialog box and returns the results of DialogCode (including Accepted and Rejected values).
If the value of the Qt:: Windows Modality attribute is not set, the dialog box displayed using the exec() method defaults to the application-level modal dialog box. All dialog boxes displayed with the exec() method block the response of all windows in the whole program before the window closes. When the exec() method is called, the dialog box will block until the dialog box closes. After closing the dialog box, the exec() method returns Accepted or Rejected, and the general program operates accordingly according to the different results returned.
The Mode dialog box has its own event loop. In the exec() method, the modal attribute is set to Qt:: Application Modal, then the show() is called to display the dialog box, and finally the event loop is enabled to prevent the end of the exec() method. Until the window closes, you get the DialogCode, exit the event loop, and finally the exec() method call ends. The code after the exec() method will continue to execute.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button = QPushButton("OK", self)

        self.resize(800, 600)
        button.clicked.connect(self.onOKClicked)

    def onOKClicked(self):
        dialog = QDialog()
        dialog.setWindowTitle("Dialog Demo")
        dialog.resize(300, 200)
        dialog.exec_()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

2,QMessageBox

QMessageBox is a general pop-up dialog box for displaying messages. It allows users to feedback messages by clicking different standard buttons. QMessageBox provides five common methods for displaying message dialogs.
warning(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create a warning message dialog box
critical(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create key error message dialog box
information(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create an information message dialog box
question(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create a Query Message Dialog Box
about(self, QWidget, p_str, p_str_1)
Create an information dialog box

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button = QPushButton("OK", self)

        self.resize(800, 600)
        button.clicked.connect(self.onOKClicked)

    def onOKClicked(self):
        button = QMessageBox.question(self, "MessageBox Title", "Are you sure to close?", QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Ok)
        if button == QMessageBox.Ok:
            print("select Ok Button")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

3,QInputDialog

QInputDialog is a standard dialog control consisting of a text box and two buttons (OK and Cancel). After the user clicks the OK button or presses the Enter key, the input information through QInputDialog can be received in the parent window.
QInputDialog.getInt Gets Standard Integer Input from the Control
QInputDialog.getItem Gets the option input of the list from the control
QInputDialog.getText Gets Standard String Input from the Control
QInputDialog.getDouble Gets Standard Floating Point Input from the Control

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button = QPushButton("OK", self)

        self.resize(800, 600)
        button.clicked.connect(self.onOKClicked)

    def onOKClicked(self):
        items = ["C++", "Python", "Java", "Go"]
        item, ok = QInputDialog.getItem(self, "Select an Item", "Programing Language", items, 0, False)
        if ok and item:
            print("selected item: ", item)

        text, ok = QInputDialog.getText(self, "Input an text", "text:")
        if ok:
            print("input text: ", text)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

4,QFontDialog

QFontDialog is a font selection dialog box that allows users to select the font size, style and format of the text displayed. QFontDialog.getFont can get the display size, style and format of text from the font selection dialog box.

import sys
from PyQt5.QtWidgets import QApplication, QFontDialog, QWidget, QPushButton
from PyQt5.QtGui import QFont

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button = QPushButton("OK", self)

        self.resize(800, 600)
        button.clicked.connect(self.onOKClicked)

    def onOKClicked(self):
        font, ok = QFontDialog.getFont()
        if ok:
            print(font.family(), font.pointSize())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

5,QFileDialog

QFileDialog is a standard dialog box for opening and saving files. QFileDialog uses file filters when opening files to display files with specified extensions.

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

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        button = QPushButton("OK", self)

        self.resize(800, 600)
        button.clicked.connect(self.onOKClicked)

    def onOKClicked(self):
        fname, _ = QFileDialog.getOpenFileName(self, "Open file", '/', "Images(*.jpg *.gif)")
        print(fname)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWidget()
    window.resize(400, 200)
    window.show()

    sys.exit(app.exec_())

Keywords: Python Qt Windows Lambda Attribute

Added by ViperG on Mon, 22 Jul 2019 17:10:41 +0300