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

来源:互联网 发布:手机网络数据不可用 编辑:程序博客网 时间:2024/04/28 20:48
 

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

        默认的item选中后的背景色(白色)

 

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

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

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

 

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

 

       //黄色的那行为选中行

 

 

   

[cpp] view plaincopyprint?
  1. //委托(代理)   
  2. class ItemDelegate : public QItemDelegate  
  3. {  
  4.     Q_OBJECT  
  5. public:  
  6.     ItemDelegate()  
  7.     {  
  8.     }  
  9.     void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const  
  10.     {  
  11.         QStyleOptionViewItem  viewOption(option);  
  12.         //高亮显示与普通显示时的前景色一致(即选中行和为选中时候的文字颜色一样)  
  13.         viewOption.palette.setColor(QPalette::HighlightedText, index.data(Qt::ForegroundRole).value<QColor>());  
  14.         QItemDelegate::paint(painter, viewOption, index);  
  15.     }  
  16. };  

 

   

[cpp] view plaincopyprint?
  1. view = new QTableView;  
  2. model = new QStandardItemModel;  
  3. view->setModel(model);  
  4. view->setItemDelegate(new ItemDelegate);  

 

  

[cpp] view plaincopyprint?
  1. if (strList[2].toDouble() >= strList[3].toDouble())  
  2.     model->item(row, 2)->setForeground(QBrush(QColor(255, 0, 0)));  
  3. else  
  4.     model->item(row, 2)->setForeground(QBrush(QColor(0, 127, 0)));  
  5. if (strList[4].toDouble() >= strList[3].toDouble())  
  6.     model->item(row, 4)->setForeground(QBrush(QColor(255, 0, 0)));  
  7. else  
  8.     model->item(row, 4)->setForeground(QBrush(QColor(0, 127, 0)));  

原创粉丝点击