需求:將行3CRTL+C復制,粘貼到CRTL+V行5
按下並釋放鍵時,以下方法將被調用:
- keyPressEvent(self,event) - 按下某一鍵時,該方法被調用直到鍵被釋放為止;
- keyReleaseEvent(self,event) - 釋放之前按下的鍵時被調用。event參數為QKeyEvent對象,包括事件的相關信息,有以下方法可調用。(詳見QKeyEvent文檔http://doc.qt.io/qt-5/qkeyevent.html)
- key():返回按下鍵的值;
- text():返回按下鍵的Unicode字符編碼信息,當按鍵為Shift, Control, Alt等時,則該函數返回的字符為空值;
- modifiers():判斷按下了哪些修飾鍵(Shift,Ctrl , Alt,等等)。
- 返回值為QtCore.Qt 類以下枚舉變量的組合: NoModifier - 沒有修飾鍵;
- ShiftModifier - 修飾鍵;
- ControlModifier - 修飾鍵;
- AltModifier - 修飾鍵;
- MetaModifier - 修飾鍵;
- KeypadModifier - 附加鍵盤上的任何按鍵;
- GroupSwitchModifier - 按下鍵(僅限X11系統)。
- isAutoRepeat(): 如果一直按着某鍵,返回True;否則,返回False;
- match(QKeySequence.StandardKey key): 如果當前的鍵組合與key相同,返回True;否則,返回False. 比如,是否按下了復制快捷鍵的代碼:
if e.matches(QtGui.QKeySequence.Copy):
print("組合鍵為 +") -
處理鍵盤按鍵時,要注意以下幾點: 控件必須可以設置為輸入焦點。有些控件,如QLabel是不能接受輸入焦點的。 捕獲鍵盤事件要使用grabKeyboard( )方法,釋放時,調用rekeaseKeyboard(). 可能攔截除和+以外的任何鍵。要攔截這兩個鍵,只能在event(self,event)中完成。 如果要讓父控件繼續收到鍵盤事件,要調用事件的ignore()方法;否則,調用accept()。
方法:
keyPressEvent(QKeyEvent) 按下某一鍵時,該方法被調用直到鍵被釋放為止
keyReleaseEvent(QKeyEvent) 鍵盤釋放時調用
注意:可以在QtAssistant中輸入Qt::Key找到所有鍵盤值,或者訪問下面鏈接查看:https://blog.csdn.net/judgejames/article/details/93191524、
下面是代碼實例
UIUIUIU.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'UIUIUIU.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(500, 600) self.layoutWidget = QtWidgets.QWidget(Form) self.layoutWidget.setGeometry(QtCore.QRect(10, 10, 481, 581)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.tableView = QtWidgets.QTableView(self.layoutWidget) self.tableView.setObjectName("tableView") self.verticalLayout.addWidget(self.tableView) self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget) self.pushButton_2.setObjectName("pushButton_2") self.verticalLayout.addWidget(self.pushButton_2) self.pushButton = QtWidgets.QPushButton(self.layoutWidget) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.pushButton_2.setText(_translate("Form", "插入行")) self.pushButton.setText(_translate("Form", "按鈕1"))
MAIN.py
from PyQt5.QtCore import pyqtSignal, Qt from PyQt5.QtGui import QStandardItemModel, QStandardItem, QKeyEvent from PyQt5.QtWidgets import QMainWindow, QApplication, QComboBox, QTableWidgetItem, QMessageBox, QAbstractItemView, qApp import sys from UIUIUIU import Ui_Form class MyMainWindow(QMainWindow, Ui_Form): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) # 初始化父類屬性 self.setupUi(self) self.pushButton_2.clicked.connect(self.test) self.gettabledata() self.tableView.setSelectionMode(QAbstractItemView.ContiguousSelection) # ctrl鍵的不連續的多個選擇 def test(self): clipboard = qApp.clipboard() test = clipboard.text() self.model.appendRow([QStandardItem(), ]) def keyPressEvent(self, QKeyEvent): # 鍵盤某個鍵被按下時調用 if QKeyEvent.key() == Qt.Key_C: # 判斷是否按下了A鍵 # key() 是普通鍵 print('按下了C鍵') if QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_C: # Ctrl-C鍵 # modifiers() 判斷修飾鍵 # Qt.NoModifier 沒有修飾鍵 # Qt.ShiftModifier Shift鍵被按下 # Qt.ControlModifier Ctrl鍵被按下 # Qt.AltModifier Alt鍵被按下 print('按下了Ctrl-C鍵') indexs = self.tableView.selectionModel().selection().indexes() # 選中一行,返回一個列表 p = [] if len(indexs) > 0: # 取第一行的索引 for i in indexs: p.append(self.model.data(i)) print(','.join(p)) clipboard = qApp.clipboard() # 獲取剪貼板 clipboard.setText(','.join(p)) if QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_V: # 兩鍵組合 print('按下了Ctrl-V鍵') clipboard = qApp.clipboard() # 獲取剪貼板 e = clipboard.text() indexs = self.tableView.selectionModel().selection().indexes() # 選中一行,返回一個列表 if len(indexs) > 0: # 取第一行的索引 for i, j in zip(indexs, list(e.split(","))): self.model.setData(i, j) if QKeyEvent.modifiers() == Qt.ControlModifier | Qt.ShiftModifier and QKeyEvent.key() == Qt.Key_A: # 三鍵組合 print('按下了Ctrl+Shift+A鍵') def gettabledata(self): # 獲取數據(數據模型model) self.set_model_data() # 將獲取到的數據綁定到tableview self.tableView.setModel(self.model) def set_model_data(self): # 生成一個四行兩列的模型 self.model = QStandardItemModel(4, 2) # 設置水平方向兩個頭標簽文本內容 self.model.setHorizontalHeaderLabels(['old', 'new']) arr = ['jak', 'tom'] for row in range(4): for colnum in range(2): # 設置文本內容 item = QStandardItem(str(arr[colnum])) # 設置每個位置的文本值 self.model.setItem(row, colnum, item) if __name__ == "__main__": # 實現界面與邏輯的分離方法很簡單,只需要新建一個CallFirstMainWin.py文件(即該文件),並繼承界面文件的主窗口類即可。 app = QApplication(sys.argv) myWin = MyMainWindow() myWin.show() sys.exit(app.exec_())