【发布时间】:2020-09-29 03:04:31
【问题描述】:
我正在使用 QTableView 构建一个自定义日历视图,并希望有一个 QItemSelectionModel 可以按天和周连续选择单元格。不确定从哪里开始,因为选择模型不与视图交互。视图的 onCurrentChange 方法给出了当前索引,在 selectionModel 中不起作用。
视图通常连接到更复杂的日历模型;这里的表格模型是为了说明。
from PyQt5.QtCore import QModelIndex, QDate
from PyQt5.QtCore import Qt, QAbstractTableModel, QItemSelectionModel
from PyQt5.QtWidgets import QTableView
import typing
class TableModel(QAbstractTableModel):
def __init__(self):
super(TableModel, self).__init__()
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QDate.longDayName(section + 1)
def data(self, index, role):
if role == Qt.DisplayRole:
return index.row() * 7 + index.column() + 1
def rowCount(self, index):
return 6
def columnCount(self, index):
return 7
class CalendarSelectionModel(QItemSelectionModel):
def __init__(self, *args, **kwargs):
super(CalendarSelectionModel, self).__init__(*args, *kwargs)
def currentChanged(self, current: QModelIndex, previous: QModelIndex) -> None:
print(current, previous)
class CalendarView(QTableView):
def __init__(self):
super(CalendarView, self).__init__()
# def currentChanged(self, current: QModelIndex, previous: QModelIndex) -> None:
# print(current)
if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication, QTableView
app = QApplication(sys.argv)
model = TableModel()
cal = CalendarView()
cal.setModel(model)
sel = CalendarSelectionModel(model)
cal.setSelectionModel(sel)
cal.show()
cal.resize(860, 640)
sys.exit(app.exec_())
【问题讨论】:
-
我想你有一个XY problem,你能详细解释一下你的背景目标吗?
-
@eyllanesc 我不确定如何进行这种自定义选择行为。例如,从 index(0, 3) 向下选择 index (1, 2) 应该选择从第 4 列开始的第一行和从第一列到第三列的第二行
-
我可能需要重写 selectionCommand 方法 doc.qt.io/qt-5/qabstractitemview.html#selectionCommand
标签: python pyqt pyqt5 qtableview