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的颜色照样变成白色的了。
对此我找到了使用代理的方法,使选中后的文字颜色和选中前的文字颜色一致(也可以灵活修改),效果如下图,代码随后。
//黄色的那行为选中行
如果我们想动态的更改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)));
相关文章推荐
- QT控制选中item的文字颜色(HighlightedText)
- QT控制选中item的文字颜色(HighlightedText) 和 QT表格交替背景色
- QT控制选中item的文字颜色(HighlightedText) 和 QT表格交替背景色
- TabBar 的selecedImage无法显示设置图片问题 和item文字颜色选中设置
- 设置 TabBarItem 选中时的图片及文字颜色
- IOS UITabBar+UINavigation(改变背景/标题文字颜色、状态图片、tabbar选中方形背景、item间距)
- android中设置ListView的选中的Item的背景颜色
- NSAttributedString用法简介,控制文字颜色,背景色等属性
- QTextEdit中选中文本修改字体与颜色,全部文本修改字体与颜色(设置调色板的前景色、背景色、文字颜色以及基色)
- iOS 如何修改tabbaritem选中后的文字颜色
- html中通过文字控制文本的颜色和字体(简单演示)
- css控制文字颜色渐变
- RadioGroup+RadioButton嵌套其他布局实现多行单选布局、自定义RadioButton选中和非选中样式、文字颜色
- 如何使鼠标单击ITEM单元格时黑色选中色变为其他颜色?(原创)
- css 选择后更改文字背景 CSS3 实现改变默认文本选中的颜色
- ListView 点击Item的时候,改变文字颜色和背景色
- listview的某个item选中后,条目颜色不消失。(实现方法一)
- AndroidListView点击Item的时候 改变文字颜色和背景色
- QT按钮背景颜色设置及文字显示位置设置
- css控制文字大小字体和颜色