【PYQT5】键盘按键触发实例


 

需求:将行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_())

相关