Dynamic layout question

  • hi every body . my eng lan is bad sorry for that.

    this is my code
    #include <QtGui>

    int main(int argc, char **argv)
    QApplication app(argc, argv);
    QWidget window;
    window.setFixedSize(320, 320); // it has ke fixed size and can not resize !
    QGridLayout *layout = new QGridLayout( &window );

    int X = ..... !!! // i dont know how many button i need
    for (int i = 0; i < X; i++) {
        QPushButton *btn = new QPushButton;
        btn->setFixedSize(40, 40);
        layout->addWidget(btn); // i dont know row and colum becase i dont know how many btn i have !!!


    i want add button and my layout put btn in smartly row and column that btns shown like table.if every body understand my means please help me . sorry . i need that for resizeable widget and layout

  • if this is my widget and layout and i add five button (b) . my layout put them like this shape



    i dont set row and column . layout do this

  • the window size is fixed and button size is fixed ,so you can compute each button's row and col by yourself.
    and also you can use qt "flowlayout":http://qt-project.org/doc/qt-4.8/layouts-flowlayout.html

  • To expand on what noregister said already:

    Your buttons are fixed size 40, and the window fixed size 320, so you know that you can have a maximum of 8 buttons per row (assuming no layout spacing or margin)

    @ int _maxPerRow = 8 @

    then just use that in your for loop, like so:

    int row = 0; int col = 0;
    for (int i = 0; i < X; i++) {
    QPushButton *btn = new QPushButton;
    btn->setFixedSize(40, 40);
    if (col >= _maxPerRow) {
    col = 0;
    Of course you can change _maxPerRow to account for whatever spacing you need...

  • in this problem the widget has a fixedSize ! but i tell about i need expand this example. i have one widget that can resiable !

  • so just calculate _maxPerRow at runtime?

    @ int _maxPerRow = myResizableWidget->width() / (btn->width() + layout->horizontalSpacing()) @

    I may be missing something, perhaps you could post an example of exactly where you are having problems.

  • i want write one program that manage pump . every pump shown with btn in my form. the user can add or remove pump that case add or remove btn in my form. i dont know how many pump exist and user can resize my widget to smaller or greater size. i want one layout that can generate the position of btn . if user resize widget to small size , remove extra btn in width (column) and put in height (row) and if user resize to greater size, Vice versa ! resize widget can occurs every time !!
    @int _maxPerRow = myResizableWidget->width() / (btn->width() + layout->horizontalSpacing())@
    its work but not everytime. of course i must remove layout margin ! or calculateted

  • tnx for your help so much.

Log in to reply

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