列自动调整为 QTableView 的大小

2021-12-09 00:00:00 qt qtableview c++

我是 Qt 的新手,我刚刚设法使 QTableView 与我的模型一起工作.它有固定的 3 列.当我打开一个窗口时,它看起来不错,但是当我调整窗口大小时,QTableView 本身会调整大小,但列的宽度保持不变.有什么内置的方法可以让它工作吗?我希望每次调整窗口大小时都调整列的大小以适应 QTableView 的边缘.

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.

推荐答案

有一个标题标志来确保 QTableView 的最后一列在调整大小时填满其父级.你可以这样设置:

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);

但是,这不会按比例调整其他列的大小.如果你也想这样做,你可以这样在你父母的 resizeEvent 中处理它:

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 类是 QMainWindow 的子类.

QParent class is subclass of QMainWindow.

相关文章