当前位置: 代码迷 >> QT开发 >> QTableWidget当前item的颜色有关问题
  详细解决方案

QTableWidget当前item的颜色有关问题

热度:34   发布时间:2016-04-25 04:29:13.0
QTableWidget当前item的颜色问题
QTableWidget选择方式为整行选择:
pTable->setSelectionBehavior(QAbstractItemView::SelectRows);
整行选择前,背景色为白色,字体颜色是黑色
选择该行后,该行背景色为蓝色,字体颜色为白色。
现在,我想实现的是:我点击一单元格,就选择了所在行,想对点击的单元格特殊处理,比如字体颜色不用白色,改为其他颜色
有什么方法?

------解决方案--------------------
设置选择整行的话,无论你之前对item设置的样式如何,当被选中一行的时候,都会重新按照选中一行时的样式,如果你想对你点击的item进行选中行后设置,必须重新实现setSelectionBehavior了。。。。
------解决方案--------------------
使用QTableView + QItemDelegate可以实现。
继承QTableView重写mousePressEvent事件,获取当前点击的行号和列号,如果当前行不是上一次选中的行,发送一个当前行改变的信号rowChanged(int row,int column),并将该信号连接到托管类的一个对象。
继承QItemDelegate,然后重写paint函数,paint在tableview显示的过程中会一直被调用,根据上面的rowChanged信号传递的参数,设置m_currentRow为当前选中的行,m_currentColumn为当前选中的列,下面是部分代码
[code=c/c++]
void ItemDelegate::paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
painter->save();
QRect cellRect = option.rect;
QBrush brush;
//需要绘制的行是选中行
if (index.row() == m_currentRow)
{
        //需要绘制的列是选中的列
        if(index.column() == m_currentColumn)
{
painter->setPen(QColor(0,0,0));//字体的颜色
painter->fillRect(cellRect,QColor(51,153,255));//背景色
}
        //只是选中行不是选中列
painter->setPen(QColor(255,255,255));
painter->fillRect(cellRect,QColor(51,153,255));
}
else
{
painter->fillRect(cellRect,QColor(255,255,255));
}
}
[/code]
  相关解决方案