Михаиллл
Михаиллл8. April 2019 08:05

Как в QML сделать растягивающийся интерфейс

qml

Добрый день.
Как в QML сделать растягивающийся интерфейс?
В Qt дизайнере можно регулировать отношение виджитов на экране через соотношение сгрупированных лэйаутов на экране. Хорошо это описанно тут
Но как это можно реализовать в QML?
Вот пример страницы, на которой тринируюсь

import QtQuick 2.4
import QtQuick.Controls 2.4

Item {
    id: page2element
    width: 400
    height: 600
    property alias page2Button0: page2Button0
    property alias page2Button1: page2Button1
    property alias page2Button2: page2Button2
    property alias page2Button3: page2Button3
    property alias page2ButtonMenu: page2ButtonMenu
    property alias page2Label1: page2Label1
    property alias page2Label2: page2Label2



    Button {
        id: page2ButtonMenu
        x: 150
        y: 493
        text: qsTr("МЕНЮ")
        anchors.horizontalCenter: parent.horizontalCenter
        font.pointSize: 18
    }

    Label {
        id: page2labe0
        x: 57
        y: 49
        width: 286
        height: 33
        text: qsTr("Выберете красный цвет")
        anchors.horizontalCenterOffset: 0
        anchors.horizontalCenter: parent.horizontalCenter
        font.family: "Verdana"
        horizontalAlignment: Text.AlignHCenter
        font.pixelSize: 22
        font.weight: Font.Thin
    }

    Label {
        id: page2Label1
        x: 122
        y: 343
        width: 156
        height: 56
        text: qsTr("Побед: ")
        anchors.horizontalCenter: parent.horizontalCenter
        horizontalAlignment: Text.AlignHCenter
        font.pointSize: 20
    }



    Label {
        id: page2Label2
        x: 122
        y: 419
        width: 156
        height: 56
        text: qsTr("1 из 20")
        anchors.horizontalCenter: parent.horizontalCenter
        horizontalAlignment: Text.AlignHCenter
        font.pointSize: 20
    }

    Row {
        id: row
        x: 29
        y: 102
        spacing: 50
        anchors.horizontalCenter: parent.horizontalCenter

        Button {
            id: page2Button0
            width: 100
            height: 100
            Image {
                id: page2image1
                width: 100
                height: 100
                anchors.rightMargin: 0
                anchors.bottomMargin: 0
                anchors.fill: parent
                source: "qrc:/images/images/close.png"
                fillMode: Image.Stretch
            }
        }

        Button {
            id: page2Button1
            width: 100
            height: 100
            Image {
                id: page2image2
                width: 100
                height: 100
                anchors.rightMargin: 0
                anchors.bottomMargin: 0
                anchors.fill: parent
                source: "qrc:/images/images/close.png"
                fillMode: Image.Stretch
            }
        }
    }

    Row {
        id: row1
        x: 57
        y: 220
        spacing: 50
        anchors.horizontalCenter: parent.horizontalCenter

        Button {
            id: page2Button2
            width: 100
            height: 100
            Image {
                id: page2image3
                width: 100
                height: 100
                anchors.leftMargin: 0
                anchors.topMargin: 0
                anchors.rightMargin: 0
                anchors.bottomMargin: 0
                anchors.fill: parent
                source: "qrc:/images/images/close.png"
                fillMode: Image.Stretch
            }
        }

        Button {
            id: page2Button3
            width: 100
            height: 100
            Image {
                id: page2image4
                width: 100
                height: 100
                anchors.rightMargin: 0
                anchors.bottomMargin: 0
                anchors.fill: parent
                source: "qrc:/images/images/close.png"
                fillMode: Image.Stretch
            }
        }
    }
    states: [
        State {
            name: "Page2State1"

            PropertyChanges {
                target: page2image1
                source: "qrc:/images/images/red.png"
            }

            PropertyChanges {
                target: page2image2
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image3
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image4
                source: "qrc:/images/images/black.png"
            }
        },
        State {
            name: "Page2State2"

            PropertyChanges {
                target: page2image1
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image2
                source: "qrc:/images/images/red.png"
            }

            PropertyChanges {
                target: page2image3
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image4
                source: "qrc:/images/images/black.png"
            }
        },
        State {
            name: "Page2State3"

            PropertyChanges {
                target: page2image1
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image2
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image3
                source: "qrc:/images/images/red.png"
            }

            PropertyChanges {
                target: page2image4
                source: "qrc:/images/images/black.png"
            }
        },
        State {
            name: "Page2State4"

            PropertyChanges {
                target: page2image1
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image4
                source: "qrc:/images/images/red.png"
            }

            PropertyChanges {
                target: page2image2
                source: "qrc:/images/images/black.png"
            }

            PropertyChanges {
                target: page2image3
                source: "qrc:/images/images/black.png"
            }
        },
        State {
            name: "Page2State0"
        }
    ]
}

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

10
Алексей Внуков
  • 8. April 2019 08:34

у тебя все элементы имеют точку привязки (х,у), используй соотношение елементов друг к другу

    Михаиллл
    • 8. April 2019 09:17

    А как это сделать. Нужно узнавать ширину и высоту дисплея?

      Алексей Внуков
      • 8. April 2019 10:32
      • (bearbeitet)

      суть. я думаю поймете, а там експеременты все покажут
      и ознакомьтесь с этим

      import QtQuick 2.4
      import QtQuick.Controls 2.4
      
      Item {
          id: page2element
          width: 400
          height: 600
      
          Label {
              id: page2labe0
              anchors
              {
                  top: parent.top
      
              }
              text: qsTr("Выберете красный цвет")
              anchors.horizontalCenter: parent.horizontalCenter
              font.family: "Verdana"
              horizontalAlignment: Text.AlignHCenter
              font.pixelSize: 22
              font.weight: Font.Thin
          }
      
          Grid {
              id: grid
              anchors
              {
                  top:page2labe0.bottom
                  left: parent.left
                  right:parent.right
              }
              height: 400
              rows: 2
              columns: 2
              spacing: 5
      
              Button {
                  id: page2Button0
                  width: parent.width/2
                  height: parent.height/2
                  Image {
                      id: page2image1
                      anchors.fill: parent
                      source: "qrc:/images/images/close.png"
                      fillMode: Image.Stretch
                  }
              }
      
              Button {
                  id: page2Button1
                  width: parent.width/2
                  height: parent.height/2
                  Image {
                      id: page2image2
                      anchors.fill: parent
                      source: "qrc:/images/images/close.png"
                      fillMode: Image.Stretch
                  }
              }
      
              Button {
                  id: page2Button2
                  width: parent.width/2
                  height: parent.height/2
                  Image {
                      id: page2image3
                      anchors.fill: parent
                      source: "qrc:/images/images/close.png"
                      fillMode: Image.Stretch
                  }
              }
      
              Button {
                  id: page2Button3
                  width: parent.width/2
                  height: parent.height/2
                  Image {
                      id: page2image4
                      anchors.fill: parent
                      source: "qrc:/images/images/close.png"
                      fillMode: Image.Stretch
                  }
              }
          }
      
      
          Column
          {
              anchors.top: grid.bottom
              anchors.bottom: page2element.bottom
              anchors.horizontalCenter: parent.horizontalCenter
              height: parent.height/3
      
              Label
              {
                  id: page2Label1
                  text: qsTr("Побед: ")
                  horizontalAlignment: Text.AlignHCenter
                  font.pointSize: 20
              }
      
              Label
              {
                  id: page2Label2
                  text: qsTr("1 из 20")
                  horizontalAlignment: Text.AlignHCenter
                  font.pointSize: 20
              }
      
      
              Button
              {
                  id: page2ButtonMenu
      
                  text: qsTr("МЕНЮ")
      
                  font.pointSize: 18
              }
          }
          states: [
              State {
                  name: "Page2State1"
      
                  PropertyChanges {
                      target: page2image1
                      source: "qrc:/images/images/red.png"
                  }
      
                  PropertyChanges {
                      target: page2image2
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image3
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image4
                      source: "qrc:/images/images/black.png"
                  }
              },
              State {
                  name: "Page2State2"
      
                  PropertyChanges {
                      target: page2image1
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image2
                      source: "qrc:/images/images/red.png"
                  }
      
                  PropertyChanges {
                      target: page2image3
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image4
                      source: "qrc:/images/images/black.png"
                  }
              },
              State {
                  name: "Page2State3"
      
                  PropertyChanges {
                      target: page2image1
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image2
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image3
                      source: "qrc:/images/images/red.png"
                  }
      
                  PropertyChanges {
                      target: page2image4
                      source: "qrc:/images/images/black.png"
                  }
              },
              State {
                  name: "Page2State4"
      
                  PropertyChanges {
                      target: page2image1
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image4
                      source: "qrc:/images/images/red.png"
                  }
      
                  PropertyChanges {
                      target: page2image2
                      source: "qrc:/images/images/black.png"
                  }
      
                  PropertyChanges {
                      target: page2image3
                      source: "qrc:/images/images/black.png"
                  }
              },
              State {
                  name: "Page2State0"
              }
          ]
      }
      
      
        Михаиллл
        • 9. April 2019 07:08

        Спасибо. Статью читал. К сожалению этот вариант страницы не запускается в скомпилированной программе. Но по такому принципу сделал нижиприведенный код. Но при этом не получилось достичь масштабируемости. Помогите пожалуйста решить это:

        import QtQuick 2.4
        import QtQuick.Controls 2.4
        
        Item {
            id: page2element
            width: 400
            height: 600
            property alias page2Button0: page2Button0
            property alias page2Button1: page2Button1
            property alias page2Button2: page2Button2
            property alias page2Button3: page2Button3
            property alias page2ButtonMenu: page2ButtonMenu
            property alias page2Label1: page2Label1
            property alias page2Label2: page2Label2
        
        
        
        
        
        
            Column {
                id: column
                spacing: 35
                anchors.horizontalCenterOffset: 0
                anchors.bottom: parent.bottom
                anchors.bottomMargin: 10
                anchors.top: parent.top
                anchors.topMargin: 10
                anchors.horizontalCenter: parent.horizontalCenter
        
                Label {
                    id: page2labe0
                    width: 286
                    height: 33
                    text: qsTr("Выберете красный цвет")
                    anchors.horizontalCenterOffset: 0
                    anchors.horizontalCenter: parent.horizontalCenter
                    font.family: "Verdana"
                    horizontalAlignment: Text.AlignHCenter
                    font.pixelSize: 22
                    font.weight: Font.Thin
                }
        
                Row {
                    id: row
                    spacing: 50
                    anchors.horizontalCenter: parent.horizontalCenter
        
                    Button {
                        id: page2Button0
                        width: 100
                        height: 100
                        Image {
                            id: page2image1
                            width: 100
                            height: 100
                            anchors.rightMargin: 0
                            anchors.bottomMargin: 0
                            anchors.fill: parent
                            source: "qrc:/images/images/close.png"
                            fillMode: Image.Stretch
                        }
                    }
        
                    Button {
                        id: page2Button1
                        width: 100
                        height: 100
                        Image {
                            id: page2image2
                            width: 100
                            height: 100
                            anchors.rightMargin: 0
                            anchors.bottomMargin: 0
                            anchors.fill: parent
                            source: "qrc:/images/images/close.png"
                            fillMode: Image.Stretch
                        }
                    }
                }
        
                Row {
                    id: row1
                    spacing: 50
                    anchors.horizontalCenter: parent.horizontalCenter
        
                    Button {
                        id: page2Button2
                        width: 100
                        height: 100
                        Image {
                            id: page2image3
                            width: 100
                            height: 100
                            anchors.leftMargin: 0
                            anchors.topMargin: 0
                            anchors.rightMargin: 0
                            anchors.bottomMargin: 0
                            anchors.fill: parent
                            source: "qrc:/images/images/close.png"
                            fillMode: Image.Stretch
                        }
                    }
        
                    Button {
                        id: page2Button3
                        width: 100
                        height: 100
                        Image {
                            id: page2image4
                            width: 100
                            height: 100
                            anchors.rightMargin: 0
                            anchors.bottomMargin: 0
                            anchors.fill: parent
                            source: "qrc:/images/images/close.png"
                            fillMode: Image.Stretch
                        }
                    }
                }
        
                Label {
                    id: page2Label1
                    width: 156
                    height: 56
                    text: qsTr("Побед: ")
                    anchors.horizontalCenter: parent.horizontalCenter
                    horizontalAlignment: Text.AlignHCenter
                    font.pointSize: 20
                }
        
                Label {
                    id: page2Label2
                    width: 156
                    height: 56
                    text: qsTr("1 из 20")
                    anchors.horizontalCenter: parent.horizontalCenter
                    horizontalAlignment: Text.AlignHCenter
                    font.pointSize: 20
                }
        
                Button {
                    id: page2ButtonMenu
                    text: qsTr("МЕНЮ")
                    anchors.horizontalCenter: parent.horizontalCenter
                    font.pointSize: 18
                }
            }
            states: [
                State {
                    name: "Page2State1"
        
                    PropertyChanges {
                        target: page2image1
                        source: "qrc:/images/images/red.png"
                    }
        
                    PropertyChanges {
                        target: page2image2
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image3
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image4
                        source: "qrc:/images/images/black.png"
                    }
                },
                State {
                    name: "Page2State2"
        
                    PropertyChanges {
                        target: page2image1
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image2
                        source: "qrc:/images/images/red.png"
                    }
        
                    PropertyChanges {
                        target: page2image3
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image4
                        source: "qrc:/images/images/black.png"
                    }
                },
                State {
                    name: "Page2State3"
        
                    PropertyChanges {
                        target: page2image1
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image2
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image3
                        source: "qrc:/images/images/red.png"
                    }
        
                    PropertyChanges {
                        target: page2image4
                        source: "qrc:/images/images/black.png"
                    }
                },
                State {
                    name: "Page2State4"
        
                    PropertyChanges {
                        target: page2image1
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image4
                        source: "qrc:/images/images/red.png"
                    }
        
                    PropertyChanges {
                        target: page2image2
                        source: "qrc:/images/images/black.png"
                    }
        
                    PropertyChanges {
                        target: page2image3
                        source: "qrc:/images/images/black.png"
                    }
                },
                State {
                    name: "Page2State0"
                }
            ]
        }
        
        
        
          Алексей Внуков
          • 9. April 2019 07:20

          а что не понравилось в моем коде выше? там ваш код который маштабируется

            Михаиллл
            • 9. April 2019 07:21

            Кажется я понял, нужно похоже так делать, тогда пропорции сохраняются

            spacing: /*50*/0.1 * page2element.width
            
              Алексей Внуков
              • 9. April 2019 07:22

              QML достаточно гибок, чтоб достичь желаемого разными способами, достаточно включить фантазию

                Михаиллл
                • 9. April 2019 07:37

                Но есть ли возможности в дизайнере это сделать, без лишнего кода?

                  Михаиллл
                  • 9. April 2019 08:05

                  А Ваш код ошибок не выдовал, но программа просто не открывала эту страницу

                    учитесь делать рауками

                      Kommentare

                      Nur autorisierte Benutzer können Kommentare posten.
                      Bitte Anmelden oder Registrieren
                      Letzte Kommentare
                      ИМ
                      Игорь Максимов5. Oktober 2024 07:51
                      Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
                      d
                      dblas55. Juli 2024 11:02
                      QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                      k
                      kmssr8. Februar 2024 18:43
                      Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                      Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                      EVA
                      EVA25. Dezember 2023 10:30
                      Boost - statisches Verknüpfen im CMake-Projekt unter Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
                      Jetzt im Forum diskutieren
                      J
                      JacobFib17. Oktober 2024 03:27
                      добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
                      JW
                      Jhon Wick1. Oktober 2024 15:52
                      Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
                      КГ
                      Кирилл Гусарев27. September 2024 09:09
                      Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
                      F
                      Fynjy22. Juli 2024 04:15
                      при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

                      Folgen Sie uns in sozialen Netzwerken