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


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

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

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

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

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

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

       //黄色的那行为选中行

     

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

     

  1. view = new QTableView;   
  2. model = new QStandardItemModel;   
  3. view->setModel(model);   
  4. view->setItemDelegate(new ItemDelegate);  

    

  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.   
  6. if (strList[4].toDouble() >= strList[3].toDouble())   
  7.     model->item(row, 4)->setForeground(QBrush(QColor(255, 0, 0)));   
  8. else  
  9.     model->item(row, 4)->setForeground(QBrush(QColor(0, 127, 0)));  

相关内容