Columns auto-resize to size of QTableView

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

I am new to QT and I have just managed to make a QTableView work with my model. It has fixed 3 columns. When I open a window, it look ok but when i resize the window, the QTableView itself gets resized but columns' width remains the same. Is there any build-in way to make it work? I want columns to resize to fit the edges of QTableView every the the window gets resized.

回答1:

There is a header flag to ensure that the QTableView's last column fills up its parent if resized. You can set it like so:

table_view->horizontalHeader()->setStretchLastSection(true); 

However, that does not resize the other columns proportionately. If you want to do that as well, you could handle it inside the resizeEvent of your parent thusly:

void QParent::resizeEvent(QResizeEvent *event) {     table_view->setColumnWidth(0, this->width()/3);     table_view->setColumnWidth(1, this->width()/3);     table_view->setColumnWidth(2, this->width()/3);      QMainWindow::resizeEvent(event); } 

QParent class is subclass of QMainWindow.



回答2:

This code equally stretchs each columns so that they fit the table's width.

table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); 

Docs:



回答3:

Widgets QTableView, QTreeView and their derived classes (such as QTableWidget) have this two usefull methods:

QHeaderView* horizontalHeader() const; QHeaderView* verticalHeader() const; 

If you open documentation for a class QHeaderView, you will find methods that set up appearance and behavior of row or column header for item views. You can resolve your problem by one of these methods:

  1. void QHeaderView::stretchLastSection( bool stretch )
    As Davy Jones mentioned.

    Example:

    QTableView *table = new QTableView();   table->horizontalHeader()->setStretchLastSection(true); 
  2. void QHeaderView::setResizeMode( ResizeMode mode )
    As mode you can set QHeaderView::Stretch or QHeaderView::ResizeToContents.
    Unfortunately this method have a drawback - after it's apply you will not be able to change size of columns (or rows) manually (in GUI) or programmatically.

    Example:

    QTableView *table = new QTableView();   table->horizontalHeader()->setResizeMode(QHeaderView::Stretch); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!