from PyQt5 import QtCore, QtWidgets, QtGui
import sys
import qevent, model


# ------------------------------------------------------------------------------
class TableView(QtWidgets.QTableView):

    currentEditor = None

    def __init__(self, parent=None):
        super().__init__(parent)

    def keyPressEvent(self, event):
        key = event.key()
        mod = int(event.modifiers())
        if key == QtCore.Qt.Key_Q and mod == QtCore.Qt.CTRL:
            self.close()
            exit()
        super().keyPressEvent(event)

    def mousePressEvent(self, event):
        print(f'>> mousePressEvent() / state() = {self.state()}, currentEditor = {self.currentEditor}')
        if self.state() == self.EditingState and self.currentEditor is not None:
            self.currentEditor.setFocus()
        else:
            QtWidgets.QTableView.mousePressEvent(self, event)


# ------------------------------------------------------------------------------
class Delegate(QtWidgets.QStyledItemDelegate):

    def __init__(self, view, parent=None):
        super().__init__(parent)
        self.view = view
        self.editor = None

    def createEditor(self, parent, option, index):
        self.editor = QtWidgets.QLineEdit(parent)
        self.view.currentEditor = self.editor
        return self.editor

    def setEditorData(self, label, index):
        model = index.model()
        v = model.data(index, QtCore.Qt.EditRole)
        model.setData(index, None, QtCore.Qt.EditRole)

    def setModelData(self, label, model, index):
        print(f'>> [setModelData()]')
        value = label.text()
        row = index.row()
        col = index.column()
        model.setData(index, value, QtCore.Qt.EditRole)

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    def eventFilter(self, target, event):
#       print(f'<delegate> {event.type()} [{qevent.desc(event)}]')

        if event.type() == QtCore.QEvent.KeyPress:
            key = event.key()
            mod = int(event.modifiers())

            # ASCII input
            if (
                key >= QtCore.Qt.Key_Space and key <= QtCore.Qt.Key_AsciiTilde and 
                (mod == QtCore.Qt.NoModifier or mod == QtCore.Qt.SHIFT)
            ):
                text = self.editor.text()
                self.editor.setText(text + event.text())
                return True

        return False


# ------------------------------------------------------------------------------
if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle('fusion')

    rowCount = 3
    columnCount = 4
    data = [
        ['foo', 'goo', 'zoo', 'moo'],
        ['bar', 'zar', 'jar', 'gar'],
        ['qux', 'lux', 'mux', 'sux']
        ]

    view = TableView()
    view.resize(550, 160)
    model = model.TableModel(data)
    view.setModel(model)
    view.show()

    delegate = Delegate(view)
    view.setItemDelegate(delegate)

    sys.exit(app.exec_())
