Подтвердить что ты не робот

Экран QML подходит для всех разрешений

Привет всем, у меня проблема с моим кодом QML. Я допустил ошибку, и я пошел на определенный размер, и теперь у меня проблема при установке приложения на другие устройства. Я вставлю вам свой код, где у меня есть ширина и высота, поэтому вы можете изменить его, чтобы показать мне, как работать с динамическим изменением размера.

Мне нужно сказать, что я вызываю qml файл из qt с помощью этого кода:

 QDeclarativeView *view= new QDeclarativeView;
    ui->setupUi(this);

    setCentralWidget(view);

    QDeclarativeContext *ctxt = view->rootContext();
    ctxt->setContextProperty("funkcije",this);
    ctxt->setContextProperty("myModel", QVariant::fromValue(MainWindow::dataList));

    view->setSource(QUrl("qrc:/gui.qml"));
    view->setResizeMode(QDeclarativeView::SizeRootObjectToView);
    showFullScreen();

И вот мой код QML:

Rectangle {

    id:window
    width: 602
    height: 1000
    anchors.fill: parent
     radius: 0
     .....


     ListView {
         id: listview1
         x: 0
         y: 219
        // width: 574
        // height: 967
         width: window.width
         height: window.height
         visible: true
         keyNavigationWraps: false
         boundsBehavior: Flickable.DragAndOvershootBounds
         opacity: 1
         maximumFlickVelocity: 2500
         anchors.leftMargin: 0
         highlightMoveSpeed: 489
         contentWidth: 0
         preferredHighlightEnd: 2
         spacing: 5
         highlightRangeMode: ListView.NoHighlightRange
         snapMode: ListView.SnapToItem
         anchors.bottomMargin: 0
         anchors.rightMargin: 0
         anchors.topMargin: 219
              anchors.fill: parent
              model: myModel
              delegate:Component {
                  //id: contactDelegate
                  Item {
                      id:it;
                      property variant myData: model
                      width: 574; height: 220
                      Column {
                          id:col
                          x: 12
                          y: 0
                          width: 561
                          height: 164
                          smooth: true
                          anchors.rightMargin: 0
                          anchors.bottomMargin: 7
                          anchors.leftMargin: 13
                          anchors.topMargin: 7
                          anchors.fill: parent
                          spacing: 15
                          ......


              highlight: Rectangle
              {
                  width: 600
                  height: 222
                  color:"black"; radius: 5; opacity: 0.7

              focus: true

              }
}

          Rectangle {
              id: rectangle1
              x: 0
              y: 0
              width: 602
              height: 219
              ......

          //dodaj korisnika
          Flipable {
              id: flipable
              x: 6
              y: 32
              width: 173
              height: 179
              .......

                   MouseArea {
                       x: 10
                       y: 9
                       width: 146
                       height: 150
                       anchors.rightMargin: 7
                       anchors.leftMargin: 10
                       anchors.topMargin: 9
                       anchors.bottomMargin: 9
                       hoverEnabled: false
                       anchors.fill: parent
                       ........

          //Brisanje korisnika
          Flipable {
              id: flipable1
              x: 408
              y: 32
              width: 175
              height: 179
              .......

                   MouseArea {
                       x: 7
                       y: 9
                       width: 153
                       height: 151
                       anchors.rightMargin: 8
                       anchors.leftMargin: 7
                       anchors.topMargin: 9
                       anchors.bottomMargin: 8
                       hoverEnabled: false
                       anchors.fill: parent
                       .......

          //promjeni korisnika
          Flipable {
              id: flipable2
              x: 208
              y: 32
              width: 176
              height: 179
             .......

                   MouseArea {
                       x: 7
                       y: 9
                       width: 73
                       height: 76
                       anchors.rightMargin: 7
                       anchors.leftMargin: 7
                       anchors.topMargin: 9
                       anchors.bottomMargin: 9
                       hoverEnabled: false
                       anchors.fill: parent
                       .......

            Text {
                id: text1
                x: 200
                y: 212
                font.pixelSize: 12
                opacity: 0
            }

            Rectangle {
                id: rectangle2
                x: 259
                y: 510
                width: 200
                height: 200
                color: "#ffffff"
                opacity: 0
            }

            TextInput {
                id: text_input1
                x: 331
                y: 233
                width: 80
                height: 20
                font.pixelSize: 12
                opacity: 0
            }

            Text {
                id: text2
                x: 136
                y: 228
                font.pixelSize: 12
                opacity: 0
            }

            Text {
                id: text3
                x: 152
                y: 314
                font.pixelSize: 12
                opacity: 0
            }

            Rectangle {
                id: rectangle3
                x: 256
                y: 293
                width: 200
                height: 200
                color: "#ffffff"
                opacity: 0
            }

            Rectangle {
                id: rectangle4
                x: 339
                y: 787
                width: 200
                height: 200
                color: "#ffffff"
                opacity: 0
            }

            Rectangle {
                id: rectangle5
                x: 270
                y: 456
                width: 200
                height: 200
                color: "#ffffff"
                opacity: 0
            }

            TextInput {
                id: text_input2
                x: 269
                y: 316
                width: 80
                height: 20
                font.pixelSize: 12
                opacity: 0
            }

            TextInput {
                id: text_input3
                x: 269
                y: 401
                width: 80
                height: 20
                font.pixelSize: 12
                opacity: 0
            }

            TextInput {
                id: text_input4
                x: 269
                y: 495
                width: 80
                height: 20
                font.pixelSize: 12
                opacity: 0
            }



            TextInput {
                id: text_input5
                x: 143
                y: 465
                width: 80
                height: 20
                text: qsTr("text")
                font.pixelSize: 12
                opacity: 0
            }



states: [
    State {
        name: "State1"

        PropertyChanges {
            target: listview1
            x: 0
            y: 1049
            width: 574
            height: 967
            visible: false
            anchors.topMargin: 1049
            anchors.rightMargin: 0
            anchors.bottomMargin: 0
            anchors.leftMargin: 0
        }



        PropertyChanges {
            target: rectangle1
            x: 0
            y: 0
            width: 602
            height: 253
            visible: true
        }

        PropertyChanges {
            target: text1
            x: 187
            y: 253
            width: 247
            height: 71
            color: "#c48d17"
            text: qsTr("Unesite novog korisnika")
            styleColor: "#e61717"
            style: "Raised"
            font.pixelSize: 31
            font.family: "Lucida Handwriting"
            verticalAlignment: "AlignVCenter"
            horizontalAlignment: "AlignHCenter"
            opacity: 1
        }

        PropertyChanges {
            target: rectangle2
            x: 251
            y: 353
            width: 258
            height: 42
            color: "#777e79"
            radius: 15
            smooth: true
            opacity: 1
        }

        PropertyChanges {
            target: text_input1
            x: 251
            y: 360
            width: 258
            height: 29
            font.pixelSize: 17
            font.family: "Lucida Handwriting"
            horizontalAlignment: "AlignHCenter"
            opacity: 1
        }

        PropertyChanges {
            target: text2
            x: 127
            y: 362
            width: 101
            height: 25
            color: "#fd0606"
            text: qsTr("Ime")
            style: "Raised"
            font.family: "Lucida Handwriting"
            font.pixelSize: 22
            verticalAlignment: "AlignVCenter"
            horizontalAlignment: "AlignHCenter"
            opacity: 1
        }

        PropertyChanges {
            target: text3
            x: 119
            y: 519
            color: "#f70606"
            text: qsTr("Prezime")
            style: "Raised"
            font.pixelSize: 20
            font.family: "Lucida Handwriting"
            verticalAlignment: "AlignVCenter"
            horizontalAlignment: "AlignHCenter"
            opacity: 1
        }

        PropertyChanges {
            target: rectangle3
            x: 251
            y: 514
            width: 258
            height: 40
            color: "#777e79"
            radius: 15
            opacity: 1
        }

        PropertyChanges {
            target: rectangle4
            x: 251
            y: 669
            width: 258
            height: 38
            color: "#777e79"
            radius: 15
            opacity: 1
        }

        PropertyChanges {
            target: rectangle5
            x: 251
            y: 823
            width: 258
            height: 36
            color: "#777e79"
            radius: 15
            opacity: 1
        }

        PropertyChanges {
            target: text_input2
            x: 251
            y: 519
            width: 258
            height: 29
            font.family: "Lucida Handwriting"
            font.pixelSize: 17
            horizontalAlignment: "AlignHCenter"
            opacity: 1
        }

        PropertyChanges {
            target: text_input3
            x: 251
            y: 674
            width: 258
            height: 29
            horizontalAlignment: "AlignHCenter"
            font.pixelSize: 17
            font.family: "Lucida Handwriting"
            opacity: 1
        }

        PropertyChanges {
            target: text_input4
            x: 251
            y: 827
            width: 258
            height: 29
            font.family: "Lucida Handwriting"
            font.pixelSize: 17
            horizontalAlignment: "AlignHCenter"
            opacity: 1
        }

        PropertyChanges {
            target: text4
            x: 127
            y: 669
            width: 85
            height: 31
            color: "#f70606"
            text: qsTr("Broj")
            style: "Raised"
            font.family: "Lucida Handwriting"
            font.pixelSize: 20
            horizontalAlignment: "AlignHCenter"
            verticalAlignment: "AlignVCenter"
            opacity: 1
        }


]
 }

Я поставил весь код с шириной и высотой, чтобы вы могли видеть, что я сделал неправильно. И, пожалуйста, если кто-то может сказать мне, как сделать его динамически заполняться.

4b9b3361

Ответ 1

К сожалению, сложно добиться совершенства, так как это может быть связано с тем, что при уменьшении размера экрана вы можете захотеть, чтобы кнопки были больше, и чтобы удалить контент с экрана, чтобы пользователь мог получить доступ и прочитать все в порядке.

Но общий подход заключается в том, чтобы установить масштабный коэффициент на стороне С++:

ctxt->setContextProperty("scale", /* put calculated scale factor here */);

И затем на стороне QML используйте все, чтобы масштабировать все объекты:

Rectangle {

    id:window
    width: 602 * scale
    height: 1000 * scale

Таким образом вы можете настроить масштабную переменную для изменения всего размера. Сказав это, многие люди получают различные файлы QML в зависимости от размера платформы.

Ответ 2

Я рекомендую вам прочитать Scalability в текущей документации Qt (4.8): она находится именно в этом разделе.

Он рекомендует эти методы (я цитирую страницу здесь), а затем предоставляет гораздо более подробную информацию.

  • Создайте отдельные определения макета верхнего уровня для каждого форм-фактора.

  • Держите макеты малыми и пусть компоненты масштабируются относительно их непосредственный родитель.

  • Определите независимые от устройства измерения, такие как dp (устройство независимые пиксели) и использовать их для масштабирования компонентов и компоновки измерение.

  • Определить макеты пропорционально с помощью встроенного макета функции QML.


Обновление 2014-11-18. Эта и видео статья очень полезна: Поддержка нескольких экранов и плотности экрана с Qt и V-Play

Обновление 2017-01-24. обновленная версия Qt 5.8 на странице "Масштабируемость", упомянутой выше.

Ответ 3

Изменение устройства, вы фактически меняете плотность пикселей экрана. Если у вас есть устройство с низким качеством отображения, оно будет иметь меньшее количество пикселей на дюйм или пикселей на сантиметр, чем устройство с дисплеем высокого качества.

Понимая это, мы можем легко разработать метод масштабирования нашего контента в соответствии с плотностью пикселей. Например, в моем случае у меня есть ноутбук, на котором я использую создателя Qt. Он имеет плотность пикселей 4. Но мой телефон Android имеет высокое качество, плотность которого составляет 16 (в 4 раза больше, чем у моего ноутбука). Это означает, что если элемент имеет ширину "X" и высоту "Y" при отображении на моем ноутбуке, на моем телефоне он будет отображаться с шириной "X" /4 и высотой "Y" /4. Таким образом, я должен масштабировать высоту и ширину на 4.

Теперь, как это реализовать? В QML у нас есть свойство "pixelDensity" под экраном объекта, которое даст вам плотность пикселей экрана, на котором вы запускаете приложение. Разделение этого по плотности экрана экрана, на котором вы протестировали свое приложение, даст вам масштабный коэффициент. Итак, теперь вам не нужно беспокоиться о других устройствах, на которых вы только что нашли плотность пикселей экрана, на которой вы сейчас работаете.

Следующий код отлично работает для меня.

property int default_pix_density: 4  //pixel density of my current screen
property int scale_factor: Screen.pixelDensity/default_pix_density
Rectangle
{
    width: 50*scale_factor
    height: 20*scale_factor
}