2016-08-30 4 views
0

Я хотел бы создать слайд-шоу, показывающее 3 элемента с изображением и меткой для каждого, выделенный элемент посередине (изображение больше и текст описания появляется под меткой).Как перемещать элементы в ListView

При нажатии соответствующей стрелки я хотел бы, чтобы элементы «скользят», а не просто появляются там, где они должны. К сожалению, код Behavior on x { NumberAnimation{...}} в делегате не делает этого.

Вот мой код:

import QtQuick 2.7 
import QtQuick.Window 2.0 

Window { 
    id: display 
    width: 500 
    height: 300 
    visible: true 

    Item { 
     id: conteneur 
     anchors.leftMargin: 50 
     height: display.height/1.2 
     width: display.width/1.2 
     anchors.horizontalCenter: parent.horizontalCenter 

     Rectangle { 
      id: boutonAvant 
      height: conteneur.height 
      anchors.verticalCenter: parent.verticalCenter 
      width: 68 
      x: -50 
      color: "transparent" 
      z: 1 

      Text { 
       id: pictureAv 
       anchors.centerIn: parent 
       text: "<" 
       font.pixelSize: 90 
      } 

      MouseArea { 
       id: buttonAvMouseArea 
       anchors.fill: parent 
       hoverEnabled: true 
       onClicked: listview.decrementCurrentIndex() 
      } 
     } 

     ListView { 
      id: listview 
      clip: true 
      orientation: ListView.Horizontal 
      width: conteneur.width 
      height: conteneur.height/1.2 
      anchors.centerIn: conteneur 
      model: myListModel 
      delegate: myDelegate 

      maximumFlickVelocity: 700 
      snapMode: ListView.SnapToItem 

      highlightFollowsCurrentItem: true 
      highlightRangeMode: ListView.StrictlyEnforceRange 
      preferredHighlightBegin: conteneur.width * 0.3 
      preferredHighlightEnd: conteneur.width * 0.3 + conteneur.width * 0.4 

      onCurrentIndexChanged: { 
       positionViewAtIndex(currentIndex, ListView.SnapPosition) 
      } 

      Component.onCompleted: { 
       currentIndex = 1 
      } 
     } 

     Rectangle { 
      id: boutonApres 
      height: conteneur.height 
      anchors.verticalCenter: parent.verticalCenter 
      x: conteneur.width - 10 
      width: 68 
      color: "transparent" 

      Text { 
       id: pictureAp 
       anchors.centerIn: parent 
       text: ">" 
       font.pixelSize: 90 
      } 

      MouseArea { 
       id: buttonApMouseArea 
       anchors.fill: parent 
       hoverEnabled: true 
       onClicked: listview.incrementCurrentIndex() 
      } 
     } 
    } 

    ListModel { 
     id: myListModel 

     ListElement { 
      name: "rectangle 0" 
      desc: "blabla" 
      mycolor: "green" 
     } 

     ListElement { 
      name: "rectangle 1" 
      desc: "blabla" 
      mycolor: "blue" 
     } 
     ListElement { 
      name: "rectangle 2" 
      desc: "blabla" 
      mycolor: "lightblue" 
     } 
     ListElement { 
      name: "rectangle 3" 
      desc: "blabla, \n with several lines for test \n and more lines \n and more lines" 
      mycolor: "gold" 
     } 
    } 

    Component { 
     id: myDelegate 

     Rectangle { 
      id: cadre 
      opacity: listview.currentIndex === index ? 1 : 0.5 
      anchors.top: parent.top 
      anchors.topMargin: listview.currentIndex === index ? 0 : 35 
      width: listview.currentIndex === index ? listview.width * 0.4 : listview.width * 0.3 
      height: conteneur.height 
      border.color: mycolor 
      color: "transparent" 

      Behavior on x { 
       NumberAnimation { 
        duration: 800 
       } 
      } 
     } 
    } 
} 
+1

Не могли бы вы предоставить минимальный пример, который запускается? Похоже, что вы оставили материал, форматирование вашего кода нарушено, и вы используете образы, к которым у нас нет доступа. – Mitch

+0

Я просто добавил пример кода – MBoh

+0

Спасибо. Я немного подрезал его. – Mitch

ответ

0

ListView наследует Flickable, который использует contentX и contentY управлять то, что видно. Модель Rectangles фактически не перемещается.

Я бы попробовал Behavior на ListViewcontentX. Обратите внимание, что в документации для positionViewAtIndex говорится, что они не манипулируют ими напрямую, потому что математика на них не предсказуема, но поведение на них может работать.

+0

Да, я тоже об этом думал ... и, к сожалению, это не дало результата – MBoh

0

Я, наконец, какой-то результат использования этого:

// В Bouton Avant:

MouseArea{ 
    id: boutonAvant 
    anchors.fill: parent 
    hoverEnabled: true 

    onClicked: { 
    pictureAp.visible = true; 
    var oldPos = listview.contentX; 
    listview.decrementCurrentIndex(); 
    var newPos = oldPos - listview.width*0.3; // listview.width*0.3 is the width of one item that is not the current one 

    if(listview.currentIndex == 0){ 
    pictureAv.visible = false; 
    } 

    anim.running = false 
    anim.from = oldPos; 
    anim.to = newPos; 
    anim.running = true; 
    } 
} 

}

элемент управления ListView становится:

ListView{ 
      id: listview 
      clip: true 
      orientation: ListView.Horizontal 
      width: conteneur.width 
      height: conteneur.height/1.2 
      anchors.centerIn: conteneur 
      model: myListModel 
      delegate: myDelegate 

      Component.onCompleted: { 
       currentIndex = 1; 
      } 

     } 

    NumberAnimation { id: anim; target: listview; property: "contentX"; duration: 800 } 

И boutonApres подобен boutonАвант с:

 MouseArea{ 
      id: buttonApMouseArea 
      anchors.fill: parent 
      hoverEnabled: true 
      onClicked: { 
       pictureAv.visible = true; 

       var oldPos = listview.contentX; 
       listview.incrementCurrentIndex(); 
       var newPos = oldPos + listview.width*0.3; 

       if(listview.currentIndex == listview.count-1){ 
        pictureAp.visible = false; 
       } 

       anim.running = false 
       anim.from = oldPos; 
       anim.to = newPos; 
       anim.running = true; 
      } 
     } 

Он работает штрафом, когда элементы, находящиеся «на слайде», находятся в середине списка, но когда я добираюсь до первого элемента (при последнем щелчке левой стрелки) или до последнего элемента (при последнем щелчке в правой стрелке), я получаю тревожный «щелчок», как если бы этот список пытался двигаться в двух местах одновременно, следуя двум различным порядкам. Но я не вижу, откуда это может произойти ...

Смежные вопросы