1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from PySide6.QtCore import (QAbstractItemModel, QDate, QModelIndex, QObject,
QStringListModel, Qt, Slot)
from PySide6.QtWidgets import (QCompleter, QDateTimeEdit, QLineEdit,
QStyleOptionViewItem, QStyledItemDelegate, QWidget)
from typing import Optional
class SpreadSheetDelegate(QStyledItemDelegate):
def __init__(self, parent: Optional[QObject] = None) -> None:
super().__init__(parent)
def create_editor(self, parent: QWidget,
option: QStyleOptionViewItem,
index: QModelIndex) -> QWidget:
if index.column() == 1:
editor = QDateTimeEdit(parent)
editor.setDisplayFormat("dd/M/yyyy")
editor.setCalendarPopup(True)
return editor
editor = QLineEdit(parent)
# create a completer with the strings in the column as model
allStrings = QStringListModel()
for i in range(1, index.model().rowCount()):
strItem = str(index.model().data(index.sibling(i, index.column()), Qt.EditRole))
if not allStrings.contains(strItem):
allStrings.append(strItem)
autoComplete = QCompleter(allStrings)
editor.setCompleter(autoComplete)
editor.editingFinished.connect(SpreadSheetDelegate.commit_and_close_editor)
return editor
@Slot()
def commit_and_close_editor(self) -> None:
editor = self.sender()
self.commitData.emit(editor)
self.closeEditor.emit(editor)
def set_editor_data(self, editor: QWidget, index: QModelIndex) -> None:
edit = QLineEdit(editor)
if edit:
edit.setText(str(index.model().data(index, Qt.EditRole)))
return
dateEditor = QDateTimeEdit(editor)
if dateEditor:
dateEditor.setDate(
QDate.fromString(
str(index.model().data(index, Qt.EditRole)), "d/M/yyyy"))
def set_model_data(self, editor: QWidget,
model: QAbstractItemModel, index: QModelIndex) -> None:
edit = QLineEdit(editor)
if edit:
model.setData(index, edit.text())
return
dateEditor = QDateTimeEdit(editor)
if dateEditor:
model.setData(index, dateEditor.date().toString("dd/M/yyyy"))
|