Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. How to horizontally center an item in a ColumnLayout in a StackLayout?
Forum Updated to NodeBB v4.3 + New Features

How to horizontally center an item in a ColumnLayout in a StackLayout?

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
2 Posts 1 Posters 149 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    mjs225
    wrote on 18 Feb 2025, 05:26 last edited by
    #1

    I want to center the Rectangle horizontally in the Window. Layout.alignment: Qt.AlignHCenter works until the StackLayout is added. How to horizontally center the Rectangle? Thanks very much.

    import QtQuick
    import QtQuick.Controls
    import QtQuick.Layouts
    Window {
    	height: 300
    	width: 240
    	visible: true
    
    	StackLayout {
    		anchors.fill: parent
    		ColumnLayout {
    			Layout.fillWidth: true
    			Layout.fillHeight: true
    			Rectangle {
    				color: "red"
    				Layout.preferredWidth: 100
    				Layout.preferredHeight: 50
    				Layout.alignment: Qt.AlignHCenter
    			}
    			// other items
    		}
    		// other items
    	}
    }
    
    1 Reply Last reply
    0
    • M Offline
      M Offline
      mjs225
      wrote on 20 Feb 2025, 00:02 last edited by
      #2

      It turns out wrapping the child Layout in an Item does the trick. Don't know why and whether this is the best solution

      import QtQuick
      import QtQuick.Controls
      import QtQuick.Layouts
      
      Window {
          height: 300
          width: 240
          visible: true
      
          StackLayout {
              anchors.fill: parent
              Item {
                  Layout.fillWidth: true
                  Layout.fillHeight: true
                  ColumnLayout {
                      anchors.fill: parent
                      Rectangle {
                          color: "red"
                          Layout.preferredWidth: 100
                          Layout.preferredHeight: 50
                          Layout.alignment: Qt.AlignHCenter // Center within ColumnLayout
                      }
                      // other items
                  }
              }
              // other items
          }
      }
      
      1 Reply Last reply
      0

      1/2

      18 Feb 2025, 05:26

      • Login

      • Login or register to search.
      1 out of 2
      • First post
        1/2
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved