如何通过点击 QtableWidget 中的删除键删除一行? [英] How to remove a row by hitting delete key in QtableWidget?

查看:279
本文介绍了如何通过点击 QtableWidget 中的删除键删除一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除 Qtablewidget 的一行而不添加按钮,只需按键盘上的 Delete 键即可.我知道,我需要使用 Key Events,但不确定如何将偶数分配给特定的 tablewidget,并且不会在 GUI 中有其他选项卡的其他部分激活键事件(长话短说:键事件只是专用于特定表).

I would like to delete a row of my Qtablewidget without adding a button and just by hitting the keyboard Delete key. I know, I need to use Key Events but not sure how to assign the even just to the specific tablewidget and the key event wouldnt be activated in the other sections where you have other tabs in the GUI (Long story short: key event just be dedicated to a specific table).

按钮删除样式:

for i in rows:
                self.tableWidget.removeRow(i)

尝试关键事件:

QtCore.Qt.Key_Delete
QtGui.QTableWidget.keyPressEvent(...,...)

推荐答案

最简单的方法是将 QTableWidget 子类化并实现自己的 keyPressEvent,例如

The easiest way is to subclass QTableWidget and implement your own keyPressEvent, e.g.

import sys
from PyQt5 import QtCore, QtWidgets

class Main(QtWidgets.QTableWidget):

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Delete:
            row = self.currentRow()
            self.removeRow(row)
        else:
            super().keyPressEvent(event)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main = Main()

    main.setColumnCount(3)
    for i in range(4):
        main.insertRow(main.rowCount())
        for j in range(main.columnCount()):
            main.setItem(i, j, QtWidgets.QTableWidgetItem(f'row {i}, column{j}'))
    main.show()
    sys.exit(app.exec_())

这篇关于如何通过点击 QtableWidget 中的删除键删除一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆