Adam Piotrowski
Adam Piotrowski

Reputation: 3295

Automatically adjust rows height in QTableView

I have a widget derived from QTableView (Qt 5.5.1) for presenting data from Postgres server. I want to automatically adjust rows height to word-wrapped content when user resizes a column with mouse:

MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
    //  ...
    connect(
        horizontalHeader(),
        SIGNAL(sectionResized(int, int, int)),
        this,
        SLOT(resizeRowsToContents()));
}

This works perfectly for a small table, but bigger tables practically are not suitable for use because of large slowdown. I would need a signal like afterSectionResized (when resizing is completed with mouse release) but there is no such event.

How can I avoid multiple table formatting when user resizes a column with mouse?

Upvotes: 1

Views: 1733

Answers (1)

klin
klin

Reputation: 121524

Define a new class (MyHeaderView) derived from QHeaderView and a new signal (resized()) emited when a user releases mouse button after a section have been resized.

myheaderview.h

class MyHeaderView : public QHeaderView
{
    Q_OBJECT

public:
    explicit MyHeaderView(QWidget *parent = 0);

signals:
    void resized();

private:
    bool resizing;
    void mouseReleaseEvent(QMouseEvent *);

private slots:
    void setResizing();
};

myheaderview.cpp

MyHeaderView::MyHeaderView(QWidget *parent)
    : QHeaderView(Qt::Horizontal, parent)
{
    resizing = false;
    connect(this,
            SIGNAL(sectionResized(int, int, int)),
            this,
            SLOT(setResizing()));
}

void MyHeaderView::setResizing()
{
    resizing = true;
}

void MyHeaderView::mouseReleaseEvent(QMouseEvent *)
{
    if (resizing) {
        resizing = false;
        emit resized();
    }
}

In MyTableView class replace the standard horizontal header with a defined header widget:

MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
    myHeaderView = new MyHeaderView(this);
    setHorizontalHeader(myHeaderView);
    connect(horizontalHeader(),
            SIGNAL(resized()),
            this,
            SLOT(resizeRowsToContents()));
}

Upvotes: 2

Related Questions