Create unusual horizontal layout with QWidgets

  • Hello, guys!
    I have a little example where green, orange and red labels:

    MainWindow::MainWindow(QWidget *parent) :
    	setMinimumSize(640, 480);
    	QWidget* centralWgt = new QWidget{ this };
    	QHBoxLayout* mainLayout = new QHBoxLayout;
    	QLabel* leftLbl = new QLabel{ this };
    	leftLbl->setStyleSheet("background-color: green;");
    	QLabel* centerLbl = new QLabel{ this };
    	centerLbl->setStyleSheet("background-color: orange;");
    	QLabel* rightLbl = new QLabel{ this };
    	rightLbl->setStyleSheet("background-color: red;");

    Independent from the main window size and label sizes I want to show the centerLbl always in the center of the central widget whereas the leftLbl move to the left side and the rightLbl always move to the right side.
    I know how to do this in QML:

    Window {
        minimumWidth: 640; minimumHeight: 480;
        visible: true
        Rectangle {
            id: leftId;
            height: parent.height;
            width: 100;
            anchors.left: parent.left;
            color: "green";
            visible: true;
        Rectangle {
            id: centerId;
            width: 50; height: parent.height;
            anchors.centerIn: parent;
            color: "orange";
            visible: true;
        Rectangle {
            id: rightId;
            width: 200; height: parent.height;
            anchors.right: parent.right;
            color: "red";
            visible: true;

    But I must avoid QML in this case.
    Could you please give me an advise how to do the same with QWidgets?

    Thanks for help!

  • Hi! I've found a solution but I'm not sure if it meets your demands :-) It behaves the way you described above but only if the elements do not collide. I've made a screenshot:


  • Hello, @Wieland!

    This is exactly what I want.
    Thank you! :)

  • @Suares Great :-)

Log in to reply

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