我想在QTableWidgetItem
中画一条线。
为了划清界线,我重新实现了 QStyledItemDelegate::paint
方法。
但是,当我滚动或选择 QTableWidget
中的项目时。
一些项目失去了它们的绘图效果。
这是我的绘画实现:
void DrawLineDelegate::paint(QPainter *poPainter, const QStyleOptionViewItem &oOption, const QModelIndex &oIndex) const
{
// Valid index ?
if(!oIndex.isValid())
// Not valid.
return;
const QRect oRect( oOption.rect );
// Painter has certain settings
poPainter->save();
// Draw line
QColor oLineColor (oIndex.data(Qt::UserRole).toString());
poPainter->setRenderHint(QPainter::Antialiasing);
poPainter->setPen(QPen(oLineColor, 2, Qt::SolidLine, Qt::RoundCap));
poPainter->drawLine(oRect.left(), // Start X-coordinate
oRect.top() - oRect.height() / 2 , // Center Height (Y-coordinate)
oRect.left() + oRect.width(), // Line width
oRect.top() - oRect.height() / 2); // Center Height (Y-coordinate)
poPainter->restore();
QStyledItemDelegate::paint( poPainter, oOption, oIndex );
}
在 TableWidget 初始化函数中,我像这样设置委托(delegate)项
ui->tableWidget->setItemDelegateForColumn(2, new DrawLineDelegate(this) );
注意:我将每个项目的颜色名称存储为 Qt::UserData
。
在 table init 上,线条绘制得很好,错误是在我玩 table 的时候。
下面是一些截图
有什么建议吗?
最佳答案
好的,感谢 Kuba Ober 的提示,我成功地解决了我的问题。
修复:
- 我没有计算行高,导致它超出了表项边界。 (所以我在 DrawLine 函数中将 '-' 切换为 '+')
- 添加了行选择突出显示处理。
- 在绘图之前移动了基本的 QStyledItemDelegate 绘制函数。
这是完整的工作答案。
void DrawLineDelegate::paint(QPainter *poPainter, const QStyleOptionViewItem &oOption, const QModelIndex &oIndex) const
{
QStyle *poStyle;
bool bSelected;
// Valid index ?
if(!oIndex.isValid())
// Not valid.
return;
QStyledItemDelegate::paint( poPainter, oOption, oIndex );
if (oIndex.column() == COLUMN_COLOR_ID) {
const QRect oRect( oOption.rect );
QColor oLineColor (oIndex.data(Qt::UserRole).toString());
QStyleOptionViewItemV4 oOptv4 = oOption;
initStyleOption(&oOptv4, oIndex);
const QWidget *poWidget = oOption.widget;
// Style option
poStyle =
poWidget ? poWidget->style() : QApplication::style();
// Set pen
poPainter->setPen(QPen(oLineColor, 2, Qt::SolidLine, Qt::RoundCap));
// Selection state
bSelected =
oOption.state&QStyle::State_Selected;
// Item selected ?
if (bSelected)
{
poPainter->setBrush(oOption.palette.highlightedText());
// This call will take care to draw line while selecting
poStyle->drawControl(QStyle::CE_ItemViewItem, &oOptv4, poPainter, poWidget);
}
// Draw line in the middle of the item
poPainter->drawLine( oRect.left(), // Start X-coordinate
oRect.top() + oRect.height() / 2, // Center Height (Y-coordinate)
oRect.left() + oRect.width(), // Line width
oRect.top() + oRect.height() / 2); // Center Height (Y-coordinate)
}
}
关于qt - QTableWidgetItem 中的绘图线渲染问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32605262/