如何为QTableWidget行绘制边框?

时间:2011-09-14 12:42:05

标签: qt qt4 qtablewidget

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

这是错误的解决方案:

/// @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 ) );

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

你的解决方案并没有错。您只需要更加选择性地绘制矩形的哪些边缘:

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 );
}

希望这有帮助!

答案 1 :(得分:0)

  #include <QTableWidget>     
  QTableWidget* table = new QTableWidget();

  table->resize(400, 250);

  table->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
  table->setColumnCount(3);
  table->setRowCount(2);

  //Set Header Label Texts Here
  table->verticalHeader ()->hide();
  table->horizontalHeader()->hide();

  table->setItem(0,0,new QTableWidgetItem("CELL 1"));
  table->setItem(0,1,new QTableWidgetItem("CELL 2"));
  table->setItem(0,2,new QTableWidgetItem("CELL 3"));

  table->setItem(1,0,new QTableWidgetItem("CELL 4"));
  table->setItem(1,1,new QTableWidgetItem("CELL 5"));
  table->setItem(1,2,new QTableWidgetItem("CELL 6"));

  table->setEditTriggers(QAbstractItemView::NoEditTriggers);
  table->setFocusPolicy(Qt::NoFocus);
  table->setSelectionMode(QAbstractItemView::NoSelection);

  table-> setObjectName (QString :: fromUtf8 ("table_"));
  table->show();

样式表:

QTableWidget
{
    background-color : none;
    gridline-color: white;    // this border for rows and columns
    color:#ffffff;
}

QTableWidget#table_{
     border:1px solid #ffffff;   // this border for total table
}

sample output

enter image description here

希望通过这种简单的方式来帮助!!!