更改 QTableView 的默认选择颜色
Change default selection color for QTableView
我正在使用带有 QAbstractTableModel 的 QTableView。
我有 subclassed QAbstractTableModel
并且在我的模型 class 中 Qt::BackgroundRole
和 Qt::ForegroundRole
我根据某些条件返回了一些颜色。
而且我有子classed QTableView
class。
当我在 table 上 select 任何 row/cell 时,row/cell 会以 tabelVeiw 的默认颜色突出显示, 它不会显示从我的模型 class 返回的颜色。
如何改变这种行为?我怎样才能 avoid/ignore 这种 QTableView
的默认着色并且只有我的模型 class 返回的颜色?
您必须使用自定义 委托。
QStyledItemDelegate
的子类并实现它的 paint()
方法,如下所示:
void MyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyleOptionViewItem itemOption(option);
initStyleOption(&itemOption, index);
if ((itemOption.state & QStyle::State_Selected) &&
(itemOption.state & QStyle::State_Active))
itemOption.palette.setColor(QPalette::Highlight, Qt::red); // set your color here
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
}
如果您想从模型中获取您选择的颜色,我建议为此目的定义一个特殊的自定义角色:
enum MyRoles
{
HighlightColorRole = Qt::UserRole
};
您的模型将使用此角色通过 QAbstractItemModel::data()
方法 return 您的自定义突出显示(选择)颜色。
在您的委托中,您可以获得这样的颜色:
QColor color = index.data(HighlightColorRole).value<QColor>();
如果您想在选中单元格时更改 QTableview 的颜色,您可以这样做:
QPalette palette = tableview->palette();
palette.setColor(QPalette::Highlight, QColor(255,255,255,100)); //set your own colors and transparency level in QColor
tableview->setPalette(palette);
我正在使用带有 QAbstractTableModel 的 QTableView。
我有 subclassed QAbstractTableModel
并且在我的模型 class 中 Qt::BackgroundRole
和 Qt::ForegroundRole
我根据某些条件返回了一些颜色。
而且我有子classed QTableView
class。
当我在 table 上 select 任何 row/cell 时,row/cell 会以 tabelVeiw 的默认颜色突出显示, 它不会显示从我的模型 class 返回的颜色。
如何改变这种行为?我怎样才能 avoid/ignore 这种 QTableView
的默认着色并且只有我的模型 class 返回的颜色?
您必须使用自定义 委托。
QStyledItemDelegate
的子类并实现它的 paint()
方法,如下所示:
void MyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyleOptionViewItem itemOption(option);
initStyleOption(&itemOption, index);
if ((itemOption.state & QStyle::State_Selected) &&
(itemOption.state & QStyle::State_Active))
itemOption.palette.setColor(QPalette::Highlight, Qt::red); // set your color here
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
}
如果您想从模型中获取您选择的颜色,我建议为此目的定义一个特殊的自定义角色:
enum MyRoles
{
HighlightColorRole = Qt::UserRole
};
您的模型将使用此角色通过 QAbstractItemModel::data()
方法 return 您的自定义突出显示(选择)颜色。
在您的委托中,您可以获得这样的颜色:
QColor color = index.data(HighlightColorRole).value<QColor>();
如果您想在选中单元格时更改 QTableview 的颜色,您可以这样做:
QPalette palette = tableview->palette();
palette.setColor(QPalette::Highlight, QColor(255,255,255,100)); //set your own colors and transparency level in QColor
tableview->setPalette(palette);