QMainWindow、QWidget、QDialog用於建立窗口,能夠直接使用,也能夠派生使用。
QMainWindow窗口包含菜單欄、工具欄、狀態欄、標題欄等,是最多見的窗口形式。
QDialog是對話框窗口的基類,主要用於執行短時間任務,或與用戶進行交互,能夠是模態或非模態的。QDialog對話框沒有菜單欄、工具欄、狀態欄等。
QWidget是Qt圖形組件的基類,能夠做爲頂層窗口,也能夠嵌入到其它組件中。app
QMainWindow是頂層窗口,QMainWindow有本身的佈局管理器,不能使用setLayout對其進行設置,佈局以下:
Menu Bar是菜單欄,Toolbars是工具欄,Dock Widgets是停靠窗口,Central Widget是中央窗口,Status Bar是狀態欄。ide
import sys from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QLabel, QDesktopWidget, QToolBar class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) # 菜單欄設置 self.menuBar = self.menuBar() self.menuBar.addAction("File") self.menuBar.addAction("View") # 工具欄設置 open = QToolBar() open.addAction("OPen") self.addToolBar(open) close = QToolBar() close.addAction("Close") self.addToolBar(close) # 中央組件設置 self.window = QWidget() self.setCentralWidget(self.window) # 狀態欄設置 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是全部GUI界面組件的基類,全部窗口和控件都直接或間接繼承自QWidget基類。工具
Qt使用統一的座標系統來定位窗口控件的位置和大小,座標系統以下:
以屏幕的左上角爲原點,即(0,0),從左向右爲X軸正向,從上向下爲Y軸正向,屏幕的座標系統用於定位頂層窗口。窗口內部有本身的座標系統,窗口座標系統以左上角爲原點,即(0,0),從左向右爲X軸正向,從上向下爲Y軸正向,原點、X軸、Y軸圍成的區域爲客戶區,在客戶區的周圍是標題欄、邊框。
intx() const;
inty() const;
int width() const;
int height() const;
x()、y()獲取窗口左上角的座標,但width()和height()獲取的是客戶區的寬和高。
geometry().x()、geometry().y()獲取客戶區的左上角座標,geometry().width()、geometry().height()獲取客戶區的寬度和高度。
frameGeometry().x()、frameGeometry().y()獲取客戶區的左上角座標,frameGeometry().width()、frameGeometry().height()獲取包含客戶區、標題欄、邊框在內的寬度和高度。佈局
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做爲一個佔位符能夠顯示不可編輯的文本、圖片、GIF動畫,QLabel是界面的標籤類,繼承自QFrame。字體
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_())
QLineEdit是單行文本框控件,能夠編輯單行字符串,用於接收用戶輸入。動畫
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) # 設置驗證器 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_())
QTextEdit是一個多行文本框編輯控件,能夠顯示、編輯多行文本編輯內容,當文本內容超出控件顯示範圍時,能夠顯示水平和垂直滾動條,QTextEdit不只能夠顯示文本,還能夠顯示HTML文檔。ui
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_())
QPushButton繼承自QAbstractButton,形狀爲長方形,文本、圖標顯示在長方形區域。spa
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_())
QRadioButton繼承自QAbstractButton,提供了一組可選的按鈕和標籤,用戶能夠選擇其中一個選項,標籤用於顯示對應的文本信息。QRadioButton是一種開關按鈕,能夠切換爲on或off,即checked或unchecked。在單選按鈕組裏,一次只能選擇一個單選按鈕,若是須要多個獨佔的按鈕組合,須要將其放到QGroupBox或QButtonGroup中。code
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_())
QCheckBox繼承自QAbstractButton,提供一組帶文本標籤的複選框,用戶能夠選擇多個選項,複選框能夠顯示文本和圖標。
除了選中、未選中,QCheckBox有第三種狀態:半選中,表示沒有變化。orm
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是下拉列表框。
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的取值範圍爲0——99,每次改變的步長值爲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_())
QSlider控件提供了一個垂直或水平的滑動條,是一個用於控制有界值的控件,容許用戶沿着水平或垂直方向在某一範圍內移動滑塊,並將滑塊所在的位置轉換成一個合法範圍內的整數值。
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_())
QDialog是對話框類,提供了三種窗口模態,非模態,模態和應用程序模態,使用setWindowModality方法設置窗口模態。
(1)非模態
非模態能夠和應用程序的其它窗×××互,使用Qt.NonModal進行設置。
(2)窗口模態
窗口模態在未處理完成當前對話框時,將阻止和對話框的父窗口進行交互,使用Qt.Modal進行設置。
(3)應用程序模態
應用程序模態阻止任何和其它窗口進行交互,使用Qt.ApplicationModal。
QDialog及其派生類對話框在ESC按鍵按下時,對話框窗口將會默認調用QDialog.reject方法,關閉對話框。
setWindowModality()方法能夠設置窗口是不是模態窗口,Qt::WindowModality默認值爲Qt::NonModal,若是沒有設置Qt::WindowModality屬性值,每次用show()方法顯示出的窗口都是非模態窗口。
使用exec()方法顯示的對話框爲模態對話框,同時會阻塞窗口的響應直到用戶關閉對話框,而且返回DialogCode(包括Accepted和Rejected兩個值)結果。
若是沒有設置Qt::WindowModality屬性值,使用exec()方法顯示出的對話框默認爲應用程序級模態對話框。全部使用exec()方法顯示的對話框在窗口關閉前會阻塞整個程序全部窗口的響應。調用exec()方法後,對話框會阻塞,直到對話框關閉纔會繼續執行。在關閉對話框後exec()方法會返回Accepted或者Rejected,通常程序根據返回不一樣的結果進行相應的操做。
模式對話框有本身的事件循環,exec() 方法內部先設置modal屬性爲Qt::ApplicationModal,而後調用 show() 顯示對話框,最後啓用事件循環來阻止exec() 方法的結束。直到窗口關閉,獲得返回結果(DialogCode),退出事件循環,最後exec()方法調用結束,exec()方法後的代碼將繼續執行。
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_())
QMessageBox是一種通用的彈出式對話框,用於顯示消息,容許用戶經過點擊不一樣的標準按鈕對消息進行反饋,QMessageBox提供了五種經常使用消息對話框的顯示方法。warning(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
建立警告消息對話框critical(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
建立關鍵錯誤消息對話框information(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
建立信息消息對話框question(self, QWidget, p_str, p_str_1, buttons, QMessageBox_StandardButtons=None, QMessageBox_StandardButton=None, *args, **kwargs)
建立詢問消息對話框about(self, QWidget, p_str, p_str_1)
建立關於信息對話框
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", "是否肯定關閉?", 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_())
QInputDialog是一個標準對話框控件,由一個文本框和兩個按鈕(OK和Cancel)組成,用戶單擊OK按鈕或按下Enter鍵後,在父窗口能夠接收經過QInputDialog輸入的信息。
QInputDialog.getInt從控件中獲取標準整型輸入
QInputDialog.getItem從控件中獲取列表的選項輸入
QInputDialog.getText從控件中獲取標準字符串輸入
QInputDialog.getDouble從控件中獲取標準浮點數輸入
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_())
QFontDialog是字體選擇對話框,可讓用戶選擇所顯示的文本的字號大小、樣式和格式。QFontDialog.getFont能夠從字體選擇對話框中獲取文本的顯示字號、樣式和格式。
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_())
QFileDialog是用於打開和保存文件的標準對話框,QFileDialog在打開文件時使用文件過濾器,用於顯示指定擴展名的文件。
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_())