【发布时间】:2021-11-01 11:57:32
【问题描述】:
我正在尝试在 pyqt 中设计一个表格小部件,以便在使用箭头键导航表格时获取行的第一列中的值。我可以使用指针在我的表类上使用 clicked.connect() 来做到这一点,但是当使用箭头键导航表时,我无法找到连接我的函数的方法。我只是对 pyqt 有所了解,并尝试从文档中弄清楚这一点,但似乎没有任何 QAbstractItemModel 工作的信号方法。不确定我是否尝试过正确的事情。我尝试将 KeyPressEvent 定义添加到我的 QAbstractTableView 类中,但无法使其正常工作 - 还尝试将 QTableView 子类化,但无济于事。当然,不确定这些尝试是否正确。这是我的基本代码,它制作了一个表格,当通过指针单击选择该行时,该表格突出显示行并打印所选行的第一列中的值,但是如果您使用箭头键导航显然没有任何打印,因为打印方法该值没有被调用。
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
test_data = [[i,j,k] for i in range(2) for j in range(2) for k in range(2)]
class TableStaticModel(QAbstractTableModel):
def __init__(self, header, data):
super(TableStaticModel, self).__init__()
self._data = data
self.header = header
def data(self, index, role=Qt.DisplayRole):
if role==Qt.DisplayRole:
return self._data[index.row()][index.column()]
if role==Qt.TextAlignmentRole:
value = self._data[index.row()][index.column()]
return Qt.AlignCenter
def rowCount(self, index):
return len(self._data)
def columnCount(self,index):
return len(self._data[0])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.header[col])
return QVariant()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
model = TableStaticModel(['A','B','C'],test_data)
self.table.setModel(model)
self.table.clicked.connect(self.get_table_row_value)
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.resizeRowsToContents()
self.table.setColumnWidth(0,83)
self.table.setColumnWidth(1,85)
self.table.setColumnWidth(2,83)
self.setCentralWidget(self.table)
def get_table_row_value(self):
index=self.table.selectionModel().currentIndex()
value=index.sibling(index.row(),0).data()
print(value)
app=QtWidgets.QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()
【问题讨论】:
标签: python python-3.x pyqt pyqt5