Search code examples
qtqtableviewqscrollarea

How to prevent QAbstractScrollArea / QTableView from horizontal scrolling?


I have a QTableView and some content in it. I want a behavior like horizontalHeader() -> setResizeMode( ResizeToContent ) but it must not create horizontal scrollbars - I mean the viewport must not be wider than the table.

Even with creating a new QHeaderView it's not so easy, since there are only a few virtual methods.

drawing to visualize the problem

Thanks in advance,

Charly

PS: I have a custom item delegate, which shortens the long texts with "...". It returns as sizeHint() the full size, but when the paint() method receives a smaller size (e.g. simulated with resizeMode() == Qt::Interactive) it crops the content.


Solution

  • New Answer

    You need to set the stretch on individual sections, I've created a simple test app:

    Screen shot of test

    test.cpp

    #include <QtGui>
    
    int main(int argc, char** argv)
    {
        QApplication app(argc, argv);
    
        QStandardItemModel mdl(3, 3); // rows, cols
        mdl.setHorizontalHeaderLabels(QStringList() << "Name" << "Size" << "Date");
        mdl.setItem(0, 0, new QStandardItem("Short name"));
        mdl.setItem(0, 1, new QStandardItem("25kb"));
        mdl.setItem(0, 2, new QStandardItem("2011/07/05"));
        mdl.setItem(1, 0, new QStandardItem("This is a long name"));
        mdl.setItem(1, 1, new QStandardItem("25kb"));
        mdl.setItem(1, 2, new QStandardItem("2011/07/05"));
        mdl.setItem(2, 0, new QStandardItem("This is a long long long long name"));
        mdl.setItem(2, 1, new QStandardItem("25kb"));
        mdl.setItem(2, 2, new QStandardItem("2011/07/05"));
    
    
        QTableView view;
        view.setModel(&mdl);
        QHeaderView* hdr = view.horizontalHeader();
        hdr->setResizeMode(0, QHeaderView::Stretch);
        hdr->setResizeMode(1, QHeaderView::ResizeToContents);
        hdr->setResizeMode(2, QHeaderView::ResizeToContents);
    
        view.show();
        return app.exec();
    }
    

    test.pro

    QT += core gui
    SOURCES=test.cpp
    

    Notice: It's important that void QHeaderView::setResizeMode(int, ResizeMode) is called when when this logical index exists, that is, when a model which defines these columns is attached to the view.


    Old Answer

    QAbstractScrollArea has the horizontalScrollBarPolicy property which can have the option ScrollBarAlwaysOff.

    Try something like:

    QAbstractScrollArea* scrollArea = // ???
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);