Search code examples
pythonpyqt5qtableview

Change Mousepointer and font color by entering a cell in Qtableview


I tried something out with QTableview and want that the mousepointer changed to "hand" and font color changed to blue if I enter a specific cell in QTableview. Is that possible? So the cell should be use like a button without being a button.


Solution

  • I provide you a demo, maybe you want this.

    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    
    import numpy as np
    
    class Model(QAbstractTableModel):
        def __init__(self):
            super().__init__()
            self._data = np.random.randint(0, 255, (5, 10))
            self._color = dict()
    
        def rowCount(self, parent: QModelIndex = ...) -> int:
            return self._data.shape[0]
    
        def columnCount(self, parent: QModelIndex = ...) -> int:
            return self._data.shape[1]
    
        def data(self, index: QModelIndex, role: int = ...) :
            if index.isValid() and role == Qt.DisplayRole:
                return str(self._data[index.row(), index.column()])
    
            if index.isValid() and role == Qt.ForegroundRole:
                if f"{index.row(),index.column()}" in self._color:
                    return self._color[f"{index.row(),index.column()}"]
    
        def setData(self, index: QModelIndex, value, role: int = ...) -> bool:
            if index.isValid() and role == Qt.ForegroundRole:
                self._color = dict()
                self._color[f"{index.row(),index.column()}"] = value
                self.dataChanged.emit(self.index(0,0), self.index(self.rowCount()-1, self.columnCount() -1))
                return True
            return super().setData(index, value, role)
    
    
    class View(QTableView):
        def mouseMoveEvent(self, e: QMouseEvent) -> None:
            index = self.indexAt(e.pos())
            if index.isValid():
                self.model().setData(index, QBrush(Qt.blue), Qt.ForegroundRole)
                self.setCursor(Qt.PointingHandCursor)
            else:
                self.setCursor(Qt.ArrowCursor)
            return super().mouseMoveEvent(e)
    
    
    app = QApplication([])
    v = View()
    v.setMouseTracking(True)
    v.setModel(Model())
    v.show()
    app.exec()