Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

left/right positioning in a scroolArea



  • greetings to everyone,
    I have a problem that I can't solve alone after several tests, here is my problem: I want that when i will be an even number the positioning of the widget i is to the right if not to the left but with my code it doesn't work, here it is:

    for(int i = 0; i < 15; ++i){
    
            WidgetTest *widget = new WidgetTest(ui->scrollAreaWidgetContents);
    
            int pair = i % 2;
            if(pair = 0){
    
                ui->scrollAreaWidgetContents->layout()->setAlignment(ui->scrollAreaWidgetContents->layout(),Qt::AlignRight);
                ui->scrollAreaWidgetContents->layout()->addWidget(widget);
            }else{
    
                ui->scrollAreaWidgetContents->layout()->setAlignment(ui->scrollAreaWidgetContents->layout(),Qt::AlignLeft);
                ui->scrollAreaWidgetContents->layout()->addWidget(widget);
            }
        }
    

    note it is in a QScrollArea that I want to add the widgets

    thank you in advance for your help


  • Lifetime Qt Champion

    Hi
    You mean like
    alt text



  • @mrjj Yeah, like that, really.


  • Lifetime Qt Champion

    @EL-jos
    Well i used a QGridLayout and simply placed them where needed.
    Im not sure bool setAlignment(QWidget *w, Qt::Alignment alignment) will work as we want
    but i didnt test it.

            gridLayout = new QGridLayout(scrollAreaWidgetContents);
    
            frame = new QFrame(scrollAreaWidgetContents);
            gridLayout->addWidget(frame, 0, 0, 1, 1);
    
            frame_7 = new QFrame(scrollAreaWidgetContents);
            gridLayout->addWidget(frame_7, 1, 2, 1, 1);
    


  • @mrjj Thank you very much for your help, but will it be possible to do it in a loop?
    since in my case I will create several widgets in a loop and I actually want some to be on the left and others on the right


  • Lifetime Qt Champion

    @EL-jos
    Hi
    Sure it is.

    QFrame *MainWindow::MakeFrame( )
    {
        QFrame *frame = new QFrame(ui->scrollAreaWidgetContents);
        frame->setFrameShape(QFrame::Box);
        frame->setFrameShadow(QFrame::Raised);
        frame->setMinimumSize(QSize(64, 64)); // make it min size so it dont get too small
        return frame;
    }
    
    void MainWindow::on_pushButton_2_released()
    {
        for (int cc = 0; cc < 12; ++cc) {
            QFrame *frame = MakeFrame();
            ui->gridLayout->addWidget(frame, cc, cc % 2, 1, 1);
        }
    }
    
    

    alt text



  • Thank you very much @mrjj j for your help because it works well; sorry for the delay in my answer, the school really took too much of my mind once again I'm sorry


Log in to reply