How to properly resize a costum QTableView with a costum QHeaderView

  • Hi,

    I've wrote some code to generate a costum TableView. It displays data from a costum TableModel which works fine. Because the data is often just "yes" or "no" I wanted to create a Costum HeaderView with vertical Text in it. That worked well! But now I want the view to resize the columns perperly but it doesn't work at all.

    I tried many different variants with all the (virtual) methods given by QHeaderView and QTableView. But the TableView doesn't resize properly. I want the columns with "yes" and "no" to be as small as possible but they are way to big. And I also want the adress columns to be at the proper size for their content.

    My question now is:
    Which methods do I have to call/overwrite to resize the TableView to its contents?

    The only real thing I coded and that worked was:

    void MyHeader::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
        const int grosse = 12;
        QString title = model()->headerData(logicalIndex,Qt::Horizontal,Qt::DisplayRole).toString();
        QLinearGradient gradient(rect.topLeft(), rect.bottomRight());
        gradient.setColorAt(0, Qt::gray);
        gradient.setColorAt(1, Qt::lightGray);
        painter->fillRect(rect, gradient);
        QFont f("Cambria Math",grosse);
        painter->translate(rect.x() + rect.width()/2-grosse/2, rect.y());
        painter->drawText(0,0, title);
    QSize MyHeader::sizeHint() const
        int height = 350;
        int width  = 20;
        return QSize(width,height);

    result image

  • @FlyingHubert
    May be
    and for Header tableView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);

  • @FlyingHubert

    Hmm okay, when i code it like this it does not work. Is that what you meant ?

    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        MyTableView *view = new MyTableView(this);
        MyHeader* header = new MyHeader(view);
        MyXmlReader* reader = new MyXmlReader;
        MyModel* model = new MyModel(reader->data());


  • Hi,

    I found my problem.
    I forgot the reimplement the Qt::SizeHintRole for the "QAbstractTableModel::headerData(...)" method. therefore the QHeaderView didn't know which size each section had and made wrong assumptions!

    Thanks anyway for th reading of the post.

    Greetings FlyingHubert

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.