How to conditionally switch between Row and Column Layout



  • What is a good pattern for conditionally inserting QML items?
    For example:
    as I've tried to show in pseudocode below, I wish to layout my items in a Column when the screen is narrow, but in a Row otherwise.

    if (parent.width < 400) {
    
        Column {
            Label {
                id: label
               text: "column label"
            }
            TextField {
                id: ceditText
                text: "column text edit"
            }
        }
    
    } else {
    
        Row {
            Label {
                id: rlabel
                text: "row label"
            }
            TextField {
                id: reditText
                text: "row text edit"
            }
        }
    
    }
    

    I can't put the javascripty conditional if/else around them in QML (or, can I?) Is there some attribute of every Item that I can use to include/exclude based on a conditional value?

    Any ideas would be helpful. Thanks.



  • Oh, I got it. For this limited case anyway, I'm conditionally switching the columns: between 2 and 1

       GridLayout {
            id: grid
            columns: ( parent.width < 200 ? 1 : 2 )
    ...
       }
    

    But, if anyone wanted to chime it, that would be helpful. This only covers most of my cases.



  • @refaQtor You can just use the flow property and leave the number of columns/rows undefined:

    GridLayout {
            id: grid
            flow:  parent.width < 200 ? GridLayout.TopToBottom : GridLayout.LeftToRight
    ...
       }
    


  • That seems like a more elegant solution to work in all cases. But, I must've mixed up something else, because the widgets overlay themselves with your suggestion. Maybe I'll try to figure it out later.
    Anyway, I've got it working the way I want now.
    Thanks!


Log in to reply
 

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