PyQt5 - 在组合框中有条件地使用颜色字段 - qsqltablemodel

时间:2017-08-10 20:41:52

标签: python pyqt pyqt5

我可以使用QSqlTableModel对QComboBox中的行进行着色吗?

我试过了:

a=self.ui.comboBox.model().index(0,0)
self.ui.comboBox.model().setData(a, QtGui.QColor('red'), 8)

之后尝试使用processEvents或setModel进行各种更新,但没有一个更新。

1 个答案:

答案 0 :(得分:1)

有几种方法可以为某些行更改背景颜色。

  1. 覆盖QSqlTableModel的数据方法
  2. class CustomSqlModel(QtSql.QSqlTableModel):
        def __init__(self, parent=None):
            QtSql.QSqlTableModel.__init__(self, parent=parent)
    
        def data(self, index, role):
            if role == QtCore.Qt.BackgroundRole:
                if index.row() in [2, 4, 5]:
                    return QtGui.QBrush(QtCore.Qt.yellow)
            return QtSql.QSqlTableModel.data(self, index, role)
    

    示例:

    combo = QComboBox()
    model = CustomSqlModel()
    model.setTable("table")
    combo.setModel(model)
    

    enter image description here

    1. 使用委托,在本例中为QStyledItemDelegate
    2. class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
          def __init__(self, parent=None):
              QtWidgets.QStyledItemDelegate.__init__(self, parent=parent)
      
          def paint(self, painter, option, index):
              if index.row() in [1, 4, 5]:
                  painter.save()
                  painter.fillRect(option.rect, QtGui.QBrush(QtCore.Qt.red))
                  painter.restore()
              QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
      

      示例:

      combo = QComboBox()
      model = QSqlTableModel()
      model.setTable("table")
      combo.setModel(model)
      combo.setItemDelegate(StyledItemDelegate())
      

      enter image description here