我正在使用 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_())
Qyouu
相关分类