Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Updating backgroundcolors of QTableView
Qt 6.11 is out! See what's new in the release blog

Updating backgroundcolors of QTableView

Scheduled Pinned Locked Moved Solved Qt for Python
3 Posts 2 Posters 610 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    Johnson9070
    wrote on last edited by
    #1

    Hi all ,

    I us the code below (form ,2 buttons,qtableview) to visualize a pandas dataframe in a QTableview using the standard model.
    Now i would like to use the 2 buttons to change the back color of a cell and a row.
    Any suggestions how to go about this ?

    Cheers , John

    import timeit
    import pandas as pd
    from PyQt5 import QtGui
    from PyQt5 import QtWidgets
    from PyQt5.QtCore import Qt, QSortFilterProxyModel
    from PyQt5.QtGui import *
    from PyQt5.uic import loadUi
    
    
    class PandasTableModel(QtGui.QStandardItemModel):
    
        def __init__(self, data, parent=None):
    
            QtGui.QStandardItemModel.__init__(self, parent)
            self._data = data
    
            for col in data.columns:
                data_col = [QtGui.QStandardItem("{}".format(x)) for x in data[col].values]
                self.appendColumn(data_col)
            return
    
        def rowCount(self, parent=None):
            return len(self._data.values)
    
        def columnCount(self, parent=None):
            return self._data.columns.size
    
        def headerData(self, x, orientation, role):
    
            if orientation == Qt.Horizontal and role == Qt.DisplayRole:
                return self._data.columns[x]
            if orientation == Qt.Vertical and role == Qt.DisplayRole:
                return self._data.index[x]
    
        def flags(self, index):
            if not index.isValid():
                return Qt.ItemIsEnabled
    
            return super().flags(index) | Qt.ItemIsEditable  # add editable flag.
    
        def setData(self, index, value, role):
    
            if role == Qt.EditRole:
                # Set the value into the frame.
                self._data.iloc[index.row(), index.column()] = value
                return True
    
            return False
            # return None
    
    
    class TableViewer(QtWidgets.QMainWindow):
    
        def __init__(self):
            super(TableViewer, self).__init__()
    
            self.ui = loadUi("QTableViewForm.ui", self)
            self.ui.cmdRun1.clicked.connect(self.Runfunction1)
            self.ui.cmdRun2.clicked.connect(self.Runfunction2)
    
            self.LoadData()
    
        def LoadData(self):
            start = timeit.default_timer()
            print('Start LoadData')
    
            data = pd.read_pickle("productdata.pkl")
            df = pd.DataFrame(data)
    
            self.model = PandasTableModel(df)
            self.proxy_model2 = QStandardItemModel()
            self.proxy_model = QSortFilterProxyModel()
            self.proxy_model.setFilterKeyColumn(-1)  # Search all columns.
            self.proxy_model.setSourceModel(self.model)
            self.proxy_model.sort(0, Qt.AscendingOrder)
            self.proxy_model.setFilterCaseSensitivity(False)
            self.tableData.setModel(self.proxy_model)
            self.inputFilterImport.setText("")
            self.inputFilterImport.textChanged.connect(lambda: self.set_filter(self.inputFilterImport.text()))
    
    
            print('Stop LoadData')
            end = timeit.default_timer()
            print("Process Time: ", (end - start))
    
        def Runfunction1(self):
            start = timeit.default_timer()
            print('Start RunFunction1')
    
    
            print('Stop Runfunction1')
            end = timeit.default_timer()
            print("Process Time: ", (end - start))
    
        def Runfunction2(self):
            start = timeit.default_timer()
            print('Start RunFunction1')
    
    
    
            print('Stop Runfunction1')
            end = timeit.default_timer()
            print("Process Time: ", (end - start))
    
        def set_filter(self, inputfilter):
    
            # print("Start set_filter")
    
            self.proxy_model.setFilterFixedString(inputfilter)
            filter_result = self.proxy_model.rowCount()
    
            # print("Stop set_filter")
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        win = TableViewer()
        win.show()
        sys.exit(app.exec_())
    
    JonBJ 1 Reply Last reply
    0
    • J Johnson9070

      Hi all ,

      I us the code below (form ,2 buttons,qtableview) to visualize a pandas dataframe in a QTableview using the standard model.
      Now i would like to use the 2 buttons to change the back color of a cell and a row.
      Any suggestions how to go about this ?

      Cheers , John

      import timeit
      import pandas as pd
      from PyQt5 import QtGui
      from PyQt5 import QtWidgets
      from PyQt5.QtCore import Qt, QSortFilterProxyModel
      from PyQt5.QtGui import *
      from PyQt5.uic import loadUi
      
      
      class PandasTableModel(QtGui.QStandardItemModel):
      
          def __init__(self, data, parent=None):
      
              QtGui.QStandardItemModel.__init__(self, parent)
              self._data = data
      
              for col in data.columns:
                  data_col = [QtGui.QStandardItem("{}".format(x)) for x in data[col].values]
                  self.appendColumn(data_col)
              return
      
          def rowCount(self, parent=None):
              return len(self._data.values)
      
          def columnCount(self, parent=None):
              return self._data.columns.size
      
          def headerData(self, x, orientation, role):
      
              if orientation == Qt.Horizontal and role == Qt.DisplayRole:
                  return self._data.columns[x]
              if orientation == Qt.Vertical and role == Qt.DisplayRole:
                  return self._data.index[x]
      
          def flags(self, index):
              if not index.isValid():
                  return Qt.ItemIsEnabled
      
              return super().flags(index) | Qt.ItemIsEditable  # add editable flag.
      
          def setData(self, index, value, role):
      
              if role == Qt.EditRole:
                  # Set the value into the frame.
                  self._data.iloc[index.row(), index.column()] = value
                  return True
      
              return False
              # return None
      
      
      class TableViewer(QtWidgets.QMainWindow):
      
          def __init__(self):
              super(TableViewer, self).__init__()
      
              self.ui = loadUi("QTableViewForm.ui", self)
              self.ui.cmdRun1.clicked.connect(self.Runfunction1)
              self.ui.cmdRun2.clicked.connect(self.Runfunction2)
      
              self.LoadData()
      
          def LoadData(self):
              start = timeit.default_timer()
              print('Start LoadData')
      
              data = pd.read_pickle("productdata.pkl")
              df = pd.DataFrame(data)
      
              self.model = PandasTableModel(df)
              self.proxy_model2 = QStandardItemModel()
              self.proxy_model = QSortFilterProxyModel()
              self.proxy_model.setFilterKeyColumn(-1)  # Search all columns.
              self.proxy_model.setSourceModel(self.model)
              self.proxy_model.sort(0, Qt.AscendingOrder)
              self.proxy_model.setFilterCaseSensitivity(False)
              self.tableData.setModel(self.proxy_model)
              self.inputFilterImport.setText("")
              self.inputFilterImport.textChanged.connect(lambda: self.set_filter(self.inputFilterImport.text()))
      
      
              print('Stop LoadData')
              end = timeit.default_timer()
              print("Process Time: ", (end - start))
      
          def Runfunction1(self):
              start = timeit.default_timer()
              print('Start RunFunction1')
      
      
              print('Stop Runfunction1')
              end = timeit.default_timer()
              print("Process Time: ", (end - start))
      
          def Runfunction2(self):
              start = timeit.default_timer()
              print('Start RunFunction1')
      
      
      
              print('Stop Runfunction1')
              end = timeit.default_timer()
              print("Process Time: ", (end - start))
      
          def set_filter(self, inputfilter):
      
              # print("Start set_filter")
      
              self.proxy_model.setFilterFixedString(inputfilter)
              filter_result = self.proxy_model.rowCount()
      
              # print("Stop set_filter")
      if __name__ == "__main__":
          import sys
          app = QtWidgets.QApplication(sys.argv)
          win = TableViewer()
          win.show()
          sys.exit(app.exec_())
      
      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by
      #2

      @Johnson9070
      There are several ways. Since you are using QStandardItems why not use QStandardItem::setBackground(const QBrush &brush)?

      1 Reply Last reply
      1
      • J Offline
        J Offline
        Johnson9070
        wrote on last edited by
        #3

        That is what i was looking for ;-)

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved