如何为 QTableWidget 行绘制边框? [英] HowTo draw border for QTableWidget row?

查看:127
本文介绍了如何为 QTableWidget 行绘制边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以不同的方式为 QTableWidget 中的行制作边框,但所有解决方案都没有响应我的要求.我想要的只是围绕整行绘制一个矩形.我曾尝试过 QStyledItemDelegate 类,但这不是我的方式,因为委托仅用于项目[行,列],而不是整个行或列.

I'm trying to make a border for rows in QTableWidget with different ways, but all solutions don't respond my requirements. All that I want, is to draw a rectangle around a whole row. I had try QStyledItemDelegate class, but that is not my way, because delegates are used only for item[ row, column ], not for the whole rows or columns.

这是错误的解决方案:

/// @brief Рисуем границу вокруг строки. 
class DrawBorderDelegate : public QStyledItemDelegate
{
public:
     DrawBorderDelegate( QObject* parent = 0 ) : QStyledItemDelegate( parent ) {}
     void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const;

}; // DrawBorderDelegate

void DrawBorderDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
     QStyleOptionViewItem opt = option;

     painter->drawRect( opt.rect );

     QStyledItemDelegate::paint( painter, opt, index );  
}

在代码中的某处:

tableWidget->setItemDelegateForRow( row, new DrawBorderDelegate( this ) );

感谢您的帮助!

推荐答案

您的解决方案并没有错.您只需要对绘制的矩形的哪些边更有选择性:

Your solution was not far wrong. You just need to be a bit more selective about which edges of the rectangle you draw:

void DrawBorderDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
     const QRect rect( option.rect );

     painter->drawLine( rect.topLeft(), rect.topRight() );
     painter->drawLine( rect.bottomLeft(), rect.bottomRight() );

     // Draw left edge of left-most cell
     if ( index.column() == 0 )
         painter->drawLine( rect.topLeft(), rect.bottomLeft() );

     // Draw right edge of right-most cell
     if ( index.column() == index.model()->columnCount() - 1 )
         painter->drawLine( rect.topRight(), rect.bottomRight() );

     QStyledItemDelegate::paint( painter, option, index );
}

希望这会有所帮助!

这篇关于如何为 QTableWidget 行绘制边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆