1, QMainWindow
1. Introduction to window types
QMainWindow, QWidget and QDialog are used to create windows. They can be used directly or derived.
QMainWindow window includes menu bar, toolbar, status bar, title bar, etc. it is the most common window form.
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. QDialog dialog box 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 and cannot be set with 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, and Status Bar is the Status Bar.
3. QMainWindow instance
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") # Toolbar settings 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_())
2, QWidget
1. Introduction to QWidget
QWidget is the base class of all GUI interface components, and all windows and controls are directly or indirectly inherited from the QWidget base class.
2. Window coordinate system
Qt uses a unified coordinate system to locate the position and size of the window control. The coordinate system is as follows:
Taking the upper left corner of the screen as the origin, i.e. (0,0), from left to right is the positive direction of X axis and from top to bottom is the positive direction of Y axis. The coordinate system of the screen is used to locate the top-level window. There is its own coordinate system inside the window. The window coordinate system takes the upper left corner as the origin, i.e. (0,0). From left to right is the positive direction of X axis, and from top to bottom is the positive direction of Y axis. The area surrounded by the origin, X axis and Y axis is the customer area, and around the customer area is the title bar and border.
int x() const; int y() const; int width() const; int height() const;
x() and 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 coordinates of the upper left corner of the customer area, geometry() width(),geometry().height() gets the width and height of the client area.
frameGeometry().x(),frameGeometry().y() get the coordinates of the upper left corner of the customer area, framegeometry() width(),frameGeometry().height() gets the width and height including the client area, title bar, and border.
3. QWidget instance
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_())
3, QLabel
1. Introduction to QLabel
As a placeholder, QLabel can display non editable text, pictures and GIF animation. QLabel is the label class of the interface, which inherits from QFrame.
2. QLabel instance
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_())
4, Text box 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) # Set up verifier 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 scroll bars. QTextEdit can display not only text, but also 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 and is rectangular in shape. Text and icons are displayed in the rectangular area.
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. Users can choose one of them. The label is used to display the corresponding text information. QRadioButton is a switch button that can be switched to on or off, i.e. checked or unchecked. In the radio button group, only one radio button can be selected at a time. If you need multiple exclusive button combinations, you need to put them into 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 check boxes with text labels. Users can select multiple options, and the check box can display text and icons.
In addition to checked and unchecked, QCheckBox has a third state: semi checked, which means there is 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_())
6, 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_())
7, QSpinBox
QSpinBox is a counter control that allows the user to select an integer value and increase or decrease the currently displayed value by clicking the up and down buttons or the up and down arrows of the keyboard. The user can also enter the current value from the edit box. By default, the value range of QSpinBox is 0-99, and the step value of each change is 1.
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_())
8, QSlider
QSlider control provides a vertical or horizontal slider, which is a control used to control bounded values. It allows users to move the slider within a certain range along the horizontal or vertical direction, and convert the position 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_())
9, Dialog control
1,QDialog
QDialog is a dialog class, which provides three window modes, non mode, mode and application mode. Use setWindowModality method to set window mode.
(1) Non modal
Modeless can interact with other windows of the application, using QT Nonmodal.
(2) Window mode
Window mode will prevent interaction with the parent window of the dialog box when the current dialog box is not processed. Use QT Modal.
(3) Application mode
Application mode prevents any interaction with other windows, using QT ApplicationModal.
QDialog and its derived class dialog box when ESC key is pressed, the dialog box window will call QDialog by default Reject method to close the dialog box.
setWindowModality() method can set whether the window is a modal window. The default value of Qt::WindowModality is Qt::NonModal. If the property value of Qt::WindowModality is not set, the window displayed by show() method every time is a non modal window.
The dialog box displayed by using exec() method is a modal dialog box. At the same time, the response of the window will be blocked until the user closes the dialog box and returns the DialogCode (including the two values of Accepted and Rejected).
If the Qt::WindowModality property value is not set, the dialog box displayed by using the exec() method defaults to the application level modal dialog box. All dialog boxes displayed with exec () method will block the response of all windows of the whole program before the window is closed. After calling the exec () method, the dialog box will block and execution will not continue until the dialog box is closed. After closing the dialog box, the exec () method will return Accepted or Rejected. Generally, the program will operate according to the different results returned.
The modal dialog box has its own event loop. The exec() method first sets the modal attribute to Qt::ApplicationModal, then calls the show() to display the dialog box, and finally enables the event loop to stop the ending of the exec() method. Until the window is closed, the return result (DialogCode) is obtained, and the event loop is exited. Finally, the call of exec() method ends, and the code after 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 used to display messages, allowing users to feedback messages by clicking different standard buttons. QMessageBox provides five display methods of common message dialog boxes.
warning(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create warning message dialog box
critical(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create critical error message dialog box
information(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create information message dialog box
question(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
Create query message dialog box
about(self, QWidget, p_str, p_str_1)
Create about 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 you want to close it?", 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, which is composed of a text box and two buttons (OK and Cancel). After the user clicks the OK button or presses the Enter key, the information entered through QInputDialog can be received in the parent window.
QInputDialog.getInt gets the standard integer input from the control
QInputDialog.getItem gets the option input of the list from the control
QInputDialog.getText gets the standard string input from the control
QInputDialog.getDouble gets the standard floating point number 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 displayed text. QFontDialog.getFont can obtain the display font 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 a file filter when opening files to display files with a specified extension.
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_())