您的位置:首页 > 编程语言 > Qt开发

QT控制选中item的文字颜色(HighlightedText)

2011-04-04 22:32 501 查看
默认的情况下,QTableView,QTableWidget等控件,当item选中后其背景色为蓝色的,文字颜色(前景色)为白色的,如图:



如果我们想动态的更改item的前景色(例如值大于零显示红色,小于零显示绿色),并且选中后文字颜色不变(这个是我想实现的,其实就是模仿一般的股票价格图表),怎么办呢? 首先在添加或者修改item的时候,可以使用:

model->item(row, column)->setForeground(QBrush(QColor(255, 0, 0))); //把表格的item的文字颜色设置为红色

但是只这样还是不够的,这样只能保证在不选中的情况下显示为红色, 若不做其他设置,选中后item的颜色照样变成白色的了。

对此我找到了使用代理的方法,使选中后的文字颜色和选中前的文字颜色一致(也可以灵活修改),效果如下图,代码随后。


//黄色的那行为选中行

//委托(代理)
class ItemDelegate : public QItemDelegate
{
Q_OBJECT
public:
ItemDelegate()
{
}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem  viewOption(option);
//高亮显示与普通显示时的前景色一致(即选中行和为选中时候的文字颜色一样)
viewOption.palette.setColor(QPalette::HighlightedText, index.data(Qt::ForegroundRole).value<QColor>());
QItemDelegate::paint(painter, viewOption, index);
}
};


view = new QTableView;
model = new QStandardItemModel;
view->setModel(model);
view->setItemDelegate(new ItemDelegate);


if (strList[2].toDouble() >= strList[3].toDouble())
model->item(row, 2)->setForeground(QBrush(QColor(255, 0, 0)));
else
model->item(row, 2)->setForeground(QBrush(QColor(0, 127, 0)));
if (strList[4].toDouble() >= strList[3].toDouble())
model->item(row, 4)->setForeground(QBrush(QColor(255, 0, 0)));
else
model->item(row, 4)->setForeground(QBrush(QColor(0, 127, 0)));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: