如何将QListView滑动到最后并从头开始?



我正在做一个用API获取新闻的项目。我可以清楚地从api获取新闻,并将它们加载到listview。

我简化了代码,以便清楚地说明我的问题。这里有两个问题…

1 -我需要滑动这个列表从上到下基本滑动动画给定的时间。(如。Y从0到en(5秒)。重要的是列表的项数是可以改变的。

2 -当动画到达列表的末尾时,我需要看到最后一个项目之后的第一个项目。但它必须是这样的;在list的最后一项之后,在滑动过程进行时必须显示第一个项(如无限列表)。

这是我的代码;

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QStringList news = {    "news01",
"news02",
"news03",
"news04",
"news05",
"news06",
"news07",
"news08",
"news09",
"news10",
"news11",
"news12",
"news13",
"news14",
"news15",
"news16",
"news17",
"news18",
"news19",
};
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("listNews",news);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0
import QtGraphicalEffects 1.0
import QtQuick.Layouts 1.3
Window {
id:pencere
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: "black"
ListView{
id: newsListView
implicitWidth: parent.width
implicitHeight: parent.height
model:listNews
spacing: 5
delegate: Rectangle {
id: delegateBackground
color:"#505051"
radius: 10
width: parent.width
height: contentContainer.height + 20
Item {
id: contentContainer
width: parent.width - 20
height: column.height
anchors.centerIn: delegateBackground
RowLayout {
width: parent.width
Rectangle {
id: newsicon
width: 16
height: 16
color: "steelblue"
Layout.alignment: Qt.AlignTop
}
ColumnLayout {
id: column
Layout.fillWidth: true
spacing: 100
Text {
Layout.fillWidth: true
Layout.alignment: Qt.AlignBottom
id: messageText
text: modelData
wrapMode: TextEdit.WordWrap
verticalAlignment: index %2 == 0 ? Text.AlignBottom : Text.AlignTop
color: "white"
}
}
}
}
}
}
}

对于第一个问题,您可以将以下内容添加到ListView中。这将触发动画,如果你按箭头键向上/向下。它并不完美,但它解释了如何使用NumberAnimations。影响ListView含量的关键是contentY的性质。如果你想滚动到新闻feed的底部,你可以通过使用ListViewWindowheightcontentHeight来计算位置。

ListView {
id: newsListView
property bool scrollUp: false
property bool scrollDown: false
focus: true
Keys.onUpPressed: newsListView.scrollUp = true
Keys.onDownPressed: newsListView.scrollDown = true
NumberAnimation on contentY {
running: newsListView.scrollDown
from: 0
to: newsListView.contentHeight
duration: 1000
onFinished: newsListView.scrollDown = false
}
NumberAnimation on contentY {
running: newsListView.scrollUp
from: newsListView.contentHeight
to: 0
duration: 1000
onFinished: newsListView.scrollUp = false
}
...
}

对于@iam_peter提出的第一个问题,您可以尝试使用NumberAnimation来动画滚动。对于第二个查询,在我看来,你可以尝试研究PathView,因为在PathView中更容易获得循环列表行为,而不需要繁琐的索引计算。

另外,请看看这个主题ListView滚动。

最新更新