Search code examples
qtqtableviewqt6

Add margins to cells of QTableView


Qt 6.8.0, here how my QTableView looks like after calling resizeColumnsToContents():

before

instead I want to still resize to the content (without specifying a global minimum width, I mean) but leaving some space after the content of each column, like this:

after

I really don't want to create my own delegate for each column just to add some space. I'm reading the documentation of QTableView but I can find a suitable property to change.

I tried to set either the margin or the padding using CSS:

qApp->setStyleSheet("QTableView::item \
{ \
    border: 0px; \
    padding-right: 10px; \
}");

but it adds the padding "outside" the useful width of the cell:

css

Is there a way to adjust the column width to the contents but adding some space?


Solution

  • Arguably, the "proper" way to do this is probably to implement a custom QStyle with sizeFromContents(QStyle::CT_ItemViewItem, ...), which is how the default delegate gets its default size.

    A "quick and dirty" way that I found is to use a custom QTableView and reimplement QTableView::sizeHintForColumn() (which reimplements QAbstractItemView's version) and add some extra padding to the default size:

        int sizeHintForColumn(int col) const override {
            return QTableView::sizeHintForColumn(col) + 4;  // "4" is extra padding in pixels
        }
    

    HTH!

    PS: Here's a version using a custom QProxyStyle (not tested)

    class AppStyle : public QProxyStyle {
      Q_OBJECT
    public:
        QSize AppStyle::sizeFromContents(ContentsType type, const QStyleOption *o, const QSize &size, const QWidget *w) const override
        {
            QSize ret = QProxyStyle::sizeFromContents(type, o, size, w);
            if (type == CT_ItemViewItem) {
                // Add some extra padding to view column.
                if (!ret.isEmpty())
                    ret.rwidth() += 4;
            }
            return ret;
        }
    
    }