最近真的是運氣不好,國慶前一天,隔壁小區有人中招了,結果國慶出不了門,好不容易國慶結束了,準備上班,結果小區又有個叼毛中招了,搞得我直接國慶放了半個月,還只能在家過,沒事干只能這里寫寫,那里弄弄,于是今天就把存貨分享給大家了~
一、什么是PyQt6? 簡單介紹一下PyQt6
1、基礎簡介
PyQt6 Digia 公司的 Qt 程式的 Python 中間件,Qt庫是最強大的GUI庫之一,PyQt6的官網:www.riverbankcomputing.co.uk/news,PyQt6是由Riverbank Computing公司開發的
PyQt6 是基于 Python 的一系列模塊,它是一個多平臺的工具包,可以在包括Unix、Windows和Mac OS在內的大部分主要作業系統上運行,PyQt6 有兩個許可證,開發人員可以在 GPL 和商業許可之間進行選擇,
2、安裝 PyQt6
pip install PyQt6
3、PyQt6 模塊
PyQt6 類是由一系列模塊組成的,包括如下的模塊:
- QtCore
- QtGui
- QtWidgets
- QtDBus
- QtNetwork
- QtHelp
- QtXml
- QtSvg
- QtSql
- QtTest
1)、 界面框架部分
主類
QLayout
繼承類
QGridLayout (網格布局)
QBoxLayout(簡單的上下布局)
QStackedLayout (可切換widget的布局)
FlowLayout
2)、 界面組件部分(其實也是Widget類)
button
label
等等
3)、 界面樣式部分
color
size
font
Icon
4)、界面互動部分
action
event
signal
slot
connect
5)、概念之間關系
QWidget 作為頁面的主體,掛載layout(框架),框架添加頁面的組件,通過 action(動作,類似于點擊),event(事件),signal(信號),slot(信號槽),connect(動作系結)產生互動
通過樣式類,類似于 Icon(圖示),大小,顏色,字體等,修改界面的細節
widget 上需要有layout,layout可以繼續添加widget,可以一直加下去
6、學習檔案
學習檔案:參考First programs in PyQt6 - center window, tooltip, quit button, message box
二、撰寫一個簡單的pyqt6程式
1、簡介
撰寫一個簡單的pyqt6程式
2、知識點
- PyQt6
- sys
3、實戰
1)、創建 python 檔案
#引入類 # Python學習交流群 279199867 from PyQt6.QtWidgets import ( QApplication, QDialog, QPushButton, QHBoxLayout, QMessageBox ) import sys if __name__ == "__main__": app = QApplication(sys.argv) window = QDialog() window.resize(400, 300) #彈出視窗 def show_msg(): QMessageBox.information(window, "資訊提示", "你點擊了我") hbox = QHBoxLayout() button = QPushButton("點擊我") button.clicked.connect(show_msg) hbox.addWidget(button) window.setLayout(hbox) #展示視窗 window.show() sys.exit(app.exec())
2)、運行結果

三、PyQt6如創建選單欄
1、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、實戰
選單欄在GUI應用程式中很常見,它是位于各種選單中的一組命令,(Mac OS 對選單欄的處理是不同的,要得到類似的結果,我們可以添加下面這行: menubar.setNativeMenuBar(False)
import sys from PyQt6.QtWidgets import QMainWindow, QApplication from PyQt6.QtGui import QIcon, QAction class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): exitAct = QAction(QIcon('exit.png'), '&Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit application') exitAct.triggered.connect(QApplication.instance().quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAct) self.setGeometry(300, 300, 350, 250) self.setWindowTitle('Simple menu') self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec()) if __name__ == '__main__': main()
上門的示例中,創建了有一個選單的選單欄,這個選單命令是終止應用,也系結了快捷鍵 Ctrl+Q,示例中也創建了一個狀態欄,
exitAct = QAction(QIcon('exit.png'), '&Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit application')
QAction 是行為抽象類,包括選單欄,工具列,或自定義鍵盤快捷方式,在上面的三行中,創建了一個帶有特定圖示和 ‘Exit’ 標簽的行為,此外,還為該行為定義了一個快捷方式,第三行創建一個狀態提示,當我們將滑鼠指標懸停在選單項上時,狀態欄中就會顯示這個提示,
exitAct.triggered.connect(QApplication.instance().quit)
當選擇指定的行為時,觸發了一個信號,這個信號連接了 QApplication 組件的退出操作,這會終止這個應用程式,
menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction)
menuBar 方法創建了一個選單欄,然后使用 addMenu 創建一個檔案選單,使用 addAction 創建一個行為,
四、PyQt6創建一個狀態欄
1、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、實戰
狀態欄是顯示狀態資訊的小部件,
import sys from PyQt6.QtWidgets import QMainWindow, QApplication class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.statusBar().showMessage('Ready') self.setGeometry(300, 300, 350, 250) self.setWindowTitle('Statusbar') self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec()) if __name__ == '__main__': main()
使用 QMainWindow 創建狀態欄
self.statusBar().showMessage(‘Ready’)
使用 QtGui.QMainWindow 方法創建狀態欄,該方法的創建了一個狀態欄,并回傳statusbar物件,再呼叫 showMessage 方法在狀態欄上顯示一條訊息,
四、Python 中創建 PyQt6 的事件物件
1、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、實戰
事件物件是一個 Python object,包含了一系列描述這個事件的屬性,具體內容要看觸發的事件,
import sys from PyQt6.QtCore import Qt from PyQt6.QtWidgets import QWidget, QApplication, QGridLayout, QLabel class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() x = 0 y = 0 self.text = f'x: {x}, y: {y}' self.label = QLabel(self.text, self) grid.addWidget(self.label, 0, 0, Qt.Alignment.AlignTop) self.setMouseTracking(True) self.setLayout(grid) self.setGeometry(300, 300, 450, 300) self.setWindowTitle('Event object') self.show() def mouseMoveEvent(self, e): x = int(e.position().x()) y = int(e.position().y()) text = f'x: {x}, y: {y}' self.label.setText(text) def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec()) if __name__ == '__main__': main()
本例中,在標簽組件里,展示了滑鼠的坐標,
self.setMouseTracking(True)
滑鼠跟蹤默認是關閉的,滑鼠移動時,組件只能在滑鼠按下的時候接收到事件,開啟滑鼠跟蹤,只移動滑鼠不按下滑鼠按鈕,也能接收到事件,
def mouseMoveEvent(self, e): x = int(e.position().x()) y = int(e.position().y()) ...
e 是事件物件,它包含了事件觸發時候的資料,通過 position().x() 和 e.position().y() 方法,能獲取到滑鼠的坐標值,
self.text = f'x: {x}, y: {y}' self.label = QLabel(self.text, self)
坐標值 x 和 y 顯示在 QLabel 組件里,
五、Python 中的 PyQt6事件觸發者
1、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、實戰
某些時候,需要知道事件的觸發者是誰,PyQt6 有獲取事件觸發者的方法,
import sys from PyQt6.QtWidgets import QMainWindow, QPushButton, QApplication class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): btn1 = QPushButton("Button 1", self) btn1.move(30, 50) btn2 = QPushButton("Button 2", self) btn2.move(150, 50) btn1.clicked.connect(self.buttonClicked) btn2.clicked.connect(self.buttonClicked) self.statusBar() self.setGeometry(300, 300, 450, 350) self.setWindowTitle('Event sender') self.show() def buttonClicked(self): sender = self.sender() msg = f'{sender.text()} was pressed' self.statusBar().showMessage(msg) def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec()) if __name__ == '__main__': main()
本例中有兩個按鈕, buttonClicked 呼叫觸發者方法確定了是哪個按鈕觸發的事件,
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
兩個按鈕系結了同一個插槽,
def buttonClicked(self): sender = self.sender() msg = f'{sender.text()} was pressed' self.statusBar().showMessage(msg)
在應用的狀態欄里,顯示了是哪個按鈕被按下,
六、Python 中 PyQt6 觸發信號
1 、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、實戰
QObject 可以主動觸發信號,下面的示例顯示了如果觸發自定義信號,
import sys from PyQt6.QtCore import pyqtSignal, QObject from PyQt6.QtWidgets import QMainWindow, QApplication class Communicate(QObject): closeApp = pyqtSignal() class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.c = Communicate() self.c.closeApp.connect(self.close) self.setGeometry(300, 300, 450, 350) self.setWindowTitle('Emit signal') self.show() def mousePressEvent(self, e): self.c.closeApp.emit() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec()) if __name__ == '__main__': main()
創建了一個叫 closeApp 的信號,在滑鼠按下的時候觸發,和關閉插槽 QMainWindow 系結,
class Communicate(QObject): closeApp = pyqtSignal()
外部 Communicate 類的屬性 pyqtSignal 創建信號,
self.c = Communicate()
self.c.closeApp.connect(self.close)
自定義信號 closeApp 系結到 QMainWindow 的關閉插槽上,
def mousePressEvent(self, event): self.c.closeApp.emit()
在視窗上點擊滑鼠按鈕的時候,觸發 closeApp 信號,程式終止,
七、Python 中 PyQt6 的拖拽操作
1、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、實戰
QDrag
QDrag 提供對基于 MIME 的拖放資料傳輸的支持,它處理拖放操作的大部分細節,傳輸的資料包含在 QMimeData 物件中
import sys from PyQt6.QtWidgets import (QPushButton, QWidget, QLineEdit, QApplication) class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent) self.setAcceptDrops(True) def dragEnterEvent(self, e): if e.mimeData().hasFormat('text/plain'): e.accept() else: e.ignore() def dropEvent(self, e): self.setText(e.mimeData().text()) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): edit = QLineEdit('', self) edit.setDragEnabled(True) edit.move(30, 65) button = Button("Button", self) button.move(190, 65) self.setWindowTitle('Simple drag and drop') self.setGeometry(300, 300, 300, 150) def main(): app = QApplication(sys.argv) ex = Example() ex.show() app.exec() if __name__ == '__main__': main()
示例展示了簡單的拖拽操作,
class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent)
...
為了完成把文本拖到 QPushButton 部件上,我們必須實作某些方法才可以,所以這里創建了一個繼承自 QPushButton 的 Button 類,
self.setAcceptDrops(True)
使用 setAcceptDrops 方法處理部件的釋放事件,
def dragEnterEvent(self, e): if e.mimeData().hasFormat('text/plain'): e.accept() else: e.ignore()
dragEnterEvent 方法,定義了我們接受的資料型別————純文本,
def dropEvent(self, e): self.setText(e.mimeData().text())
dropEvent 方法,處理釋放事件————修改按鈕組件的文本,
edit = QLineEdit('', self) edit.setDragEnabled(True)
QLineEdit 部件支持拖放操作,這里只需要呼叫 setDragEnabled 方法激活它,
八、Python 中 PyQt6 的拖放按鈕組件
1、主要知識點
- 檔案讀寫
- 基礎語法
- PyQt6
- sys
2、菜鳥實戰
創建檔案!
import sys from PyQt6.QtCore import Qt, QMimeData from PyQt6.QtGui import QDrag from PyQt6.QtWidgets import QPushButton, QWidget, QApplication class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent) def mouseMoveEvent(self, e): if e.buttons() != Qt.MouseButtons.RightButton: return mimeData = QMimeData() drag = QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(e.position().toPoint() - self.rect().topLeft()) dropAction = drag.exec(Qt.DropActions.MoveAction) def mousePressEvent(self, e): super().mousePressEvent(e) if e.button() == Qt.MouseButtons.LeftButton: print('press') class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setAcceptDrops(True) self.button = Button('Button', self) self.button.move(100, 65) self.setWindowTitle('Click or Move') self.setGeometry(300, 300, 550, 450) def dragEnterEvent(self, e): e.accept() def dropEvent(self, e): position = e.position() self.button.move(position.toPoint()) e.setDropAction(Qt.DropActions.MoveAction) e.accept() def main(): app = QApplication(sys.argv) ex = Example() ex.show() app.exec() if __name__ == '__main__': main()
本例中,視窗里有個 QPushButton,滑鼠左鍵點擊它,會在控制臺列印 'press’訊息,滑鼠右鍵可以點擊拖拽它,
class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent)
基于 QPushButton 創建了一個 Button 類,并實作了兩個 QPushButton 方法:mouseMoveEvent 和 mousePressEvent,mouseMoveEvent 方法是處理拖放操作開始的地方,
if e.buttons() != Qt.MouseButtons.RightButton: return
定義滑鼠右鍵為觸發拖拽操作的按鈕,滑鼠左鍵只會觸發點擊事件,
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.position().toPoint() - self.rect().topLeft())
創建 QDrag 物件,以提供基于 MIME 資料型別的拖拽操作,
dropAction = drag.exec(Qt.DropActions.MoveAction)
drag 物件的 exec 方法執行拖拽操作,
def mousePressEvent(self, e): super().mousePressEvent(e) if e.button() == Qt.MouseButtons.LeftButton: print('press')
如果滑鼠左鍵點擊按鈕,會在控制臺列印 ‘press’ 訊息,注意,這里在父級上也呼叫了 mousePressEvent 方法,不然按鈕按下的動作不會展現出來,
position = e.pos() self.button.move(position)
dropEvent 方法處理滑鼠釋放按鈕后的操作————把組件的位置修改為滑鼠當前坐標,
e.setDropAction(Qt.MoveAction) e.accept()
使用 setDropAction 指定拖放操作的型別————滑鼠移動,
兄弟們,今天的分享就暫時到這里,下次見!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516319.html
標籤:Python
