對qt 中gridlayout的一點註解
阿新 • • 發佈:2019-01-30
剛學qt,對它的gridlayout功能非常欣賞 -- 不用自己去考慮如何安放控制元件了,layout自動把它們放好。但是今天發現自己對layout的功能並沒完全吃透。以前一直認為控制元件放到layout裡面,只要動用了setColumnStretch和setRowStretch函式,控制元件的尺寸就被按比例縮放了。其實不然。看下面的程式碼:
注意紅色部分。第一句紅語句已經把mp_View的尺寸變成了layout長寬的各 4/10。在下圖裡面也可以看到,藍色區域確實是整個layout的40%。但是,圖的最下方輸出的debug資訊表明:mp_View的寬度是640,甚至還大於layout的400!這說明,layout並沒有改變mp_View的實際大小。#include "mainwindow.h" #include "ui_mainwindow.h" #include <QBrush> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QBrush brh(Qt::blue); mp_gLayout = new QGridLayout; mp_gLayout->setColumnStretch(0,1); mp_gLayout->setColumnStretch(1,1); mp_gLayout->setColumnStretch(2,1); mp_gLayout->setColumnStretch(3,1); mp_gLayout->setColumnStretch(4,1); mp_gLayout->setColumnStretch(5,1); mp_gLayout->setColumnStretch(6,1); mp_gLayout->setColumnStretch(7,1); mp_gLayout->setColumnStretch(8,1); mp_gLayout->setColumnStretch(9,1); mp_gLayout->setRowStretch(0,1); mp_gLayout->setRowStretch(1,1); mp_gLayout->setRowStretch(2,1); mp_gLayout->setRowStretch(3,1); mp_gLayout->setRowStretch(4,1); mp_gLayout->setRowStretch(5,1); mp_gLayout->setRowStretch(6,1); mp_gLayout->setRowStretch(7,1); mp_gLayout->setRowStretch(8,1); mp_gLayout->setRowStretch(9,1); mp_View = new QGraphicsView; mp_View->setBackgroundBrush(brh); mp_Scene = new QGraphicsScene; mp_Rect = new QGraphicsRectItem; mp_Scene->addItem(mp_Rect); mp_View->setScene(mp_Scene); <span style="color:#ff0000;">mp_gLayout->addWidget(mp_View, 3,3,4,4); qDebug("width = %d, viewWidth = %d", width(), mp_View->width());</span> ui->centralWidget->setLayout(mp_gLayout); mp_Rect->setRect(0,0,mp_View->width()/5,mp_View->height()/5); mp_View->show(); } MainWindow::~MainWindow() { delete mp_Rect; delete mp_Scene; delete mp_View; delete mp_gLayout; delete ui; }