16,818
社区成员




如题,由QTableWidget派生出一个自定义的CustomTableWidget,并创建其右键菜单,通过右键菜单选择指定的单元格修改它的背景颜色,具体代码如下:
void CustomTableWidget::onActBgColor()
{
this->item(index.row(), index.column())->setBackground(Qt::yellow);
m_styleItemDelegate->setEnableClicked(true);
m_styleItemDelegate->setBgColor(Qt::yellow);
update();
}
相应的QStyledItemDelegate派生类的代理代码如下:
void CustomStyleItemDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem viewOption(option);
initStyleOption(&viewOption, index);
QTextOption op;
op.setAlignment(Qt::AlignCenter);
//QModelIndexList indexs = selectionModel()->selectedIndexes();
if(option.state.testFlag(QStyle::State_HasFocus))
{
viewOption.state = viewOption.state ^ QStyle::State_HasFocus;
viewOption.palette.setColor(QPalette::Normal, QPalette::HighlightedText, Qt::black);
}
if (option.state.testFlag(QStyle::State_Selected))
{
if(m_isClicked)
{
painter->setPen(m_backgroundColor);
painter->setBrush(m_backgroundColor);
painter->fillRect(viewOption.rect, m_backgroundColor);
//painter->drawText(viewOption.rect, index.data(Qt::DisplayRole).toString(), op); ->文本显示无效
}
else
{
viewOption.state &= ~QStyle::State_Selected;
}
}
QStyledItemDelegate::paint(painter, viewOption, index);
}
各位大佬,帮忙看看,为什么右键菜单后,虽然改变了指定单元格的背景颜色,但是单元格的内容却不见了,有什么办法可以让修改背景颜色的同时,又不丢失其内容吗?小弟在线等,欢迎各位大佬们指点一二,在此感激不尽!!!