How to set line style for specific cell in QTableView?

I work with the QT GUI. I am using a simple hex control with a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hexadecimal bytes, and then an ASCII representation of this data in the seventeenth column. Ideally, I would like to edit / set the style of the seventeenth column so that there are no lines at the top and bottom of each cell, so that the text looks free flowing. What is the best way to approach this with QTableView?

+3
source share
1 answer

I might think of several ways to do what you need; both will include custom mesh drawing, since there seems to be no direct way to connect to the QTableView class's mesh drawing routine:

1. Switch the standard grid for your treeview grid by calling setShowGrid (false) and draw grid lines for the cells that need them using the element delegate. The following is an example:

// custom item delegate to draw grid lines around cells
class CustomDelegate : public QStyledItemDelegate
{
public:
    CustomDelegate(QTableView* tableView);
protected:
    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
private:
    QPen _gridPen;
};

CustomDelegate::CustomDelegate(QTableView* tableView)
{
    // create grid pen
    int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4());
    QColor gridColor = static_cast<QRgb>(gridHint);
    _gridPen = QPen(gridColor, 0, tableView->gridStyle());
}

void CustomDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyledItemDelegate::paint(painter, option, index);

    QPen oldPen = painter->pen();
    painter->setPen(_gridPen);

    // paint vertical lines
    painter->drawLine(option.rect.topRight(), option.rect.bottomRight());
    // paint horizontal lines 
    if (index.column()!=1) //<-- check if column need horizontal grid lines
        painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());

    painter->setPen(oldPen);
}

// set up for your tree view:
ui->tableView->setShowGrid(false);
ui->tableView->setItemDelegate(new CustomDelegate(ui->tableView));

2. Create a QTableView descendant and override the paintEvent method . There you can either draw your own grid, or let the base class draw it, and then draw horizontal lines on top of the grid using the background color of the table.

hope this helps, believes

+3
source

Source: https://habr.com/ru/post/1742890/


All Articles