Qt quick listview pull-down to refresh data

Source: Internet
Author: User
Tags emit rowcount

The listview in QT quick is a derived class of flickable. When you drag your mouse or touch your fingers (touch screen), two signals, namely, flickstarted and flickended, are generated, the pull-down refresh data can be implemented. Of course, the pull-up refresh is also possible.

Create a QT quick app project and add the dynamicmodel. h and dynamicmodel. cpp files to implement dynamiclistmodel. For details about the project creation process, see "Hello world for Qt quick".

The pull-down refresh we implemented has a special effect. After each refresh, we only keep the predefined Number of pages. For example, the default page size in the Code is 20.

All rights reserved foruok. For more information, see http://blog.csdn.net/foruok.

C ++ model implementation

It's very easy to go directly to the code.

Dynamic. h:

#ifndef DYNAMICMODEL_H#define DYNAMICMODEL_H#include <QAbstractListModel>class DynamicListModelPrivate;class DynamicListModel : public QAbstractListModel{    Q_OBJECT    Q_PROPERTY(int pageSize READ pageSize WRITE setPageSize NOTIFY pageSizeChanged)    Q_PROPERTY(int total READ total WRITE setTotal NOTIFY totalChanged)public:    DynamicListModel(QObject *parent = 0);    ~DynamicListModel();    int rowCount(const QModelIndex &parent) const;    QVariant data(const QModelIndex &index, int role) const;    QHash<int, QByteArray> roleNames() const;    Q_INVOKABLE void loadMore(bool forward);    int pageSize();    void setPageSize(int size);    int total();    void setTotal(int total);signals:    void pageSizeChanged(int size);    void totalChanged(int total);private:    DynamicListModelPrivate *m_dptr;};#endif // DYNAMICMODEL_H

Dynamicmodel. cpp:

#include "dynamicModel.h"#include <QDebug>class DynamicListModelPrivate{public:    DynamicListModelPrivate(DynamicListModel *model)        : m_model(model), m_start(0), m_end(20)        , m_total(100), m_pageSize(20)    {        m_roleNames.insert(Qt::UserRole, "content");    }    void pageDown()    {        if(m_end < m_total)        {            m_start += m_pageSize;            m_end += m_pageSize;            if(m_end > m_total)            {                m_end = m_total;                m_start = m_end - m_pageSize;            }        }    }    void pageUp()    {        if(m_start > 0)        {            m_start -= m_pageSize;            if(m_start < 0) m_start = 0;            m_end = m_start + m_pageSize;        }    }    void adjustPageRange()    {        if(m_end - m_start < m_pageSize)        {            m_end = m_start + m_pageSize;            if(m_end > m_total)            {                m_end = m_total;                m_start = m_end - m_pageSize;            }        }    }    DynamicListModel *m_model;    int m_start;    int m_end;    int m_total;    int m_pageSize;    QHash<int, QByteArray> m_roleNames;};DynamicListModel::DynamicListModel(QObject *parent)    : QAbstractListModel(parent),    m_dptr(new DynamicListModelPrivate(this)){}DynamicListModel::~DynamicListModel(){    delete m_dptr;}int DynamicListModel::rowCount(const QModelIndex &parent) const{    return m_dptr->m_end - m_dptr->m_start;}QVariant DynamicListModel::data(const QModelIndex &index, int role) const{    int row = index.row();    //qDebug() << "index.row - " << row << " start - " << m_dptr->m_start;    return QString::number(row + m_dptr->m_start);}QHash<int, QByteArray> DynamicListModel::roleNames() const{    return m_dptr->m_roleNames;}void DynamicListModel::loadMore(bool forward){    beginResetModel();    if(forward)m_dptr->pageDown();    else m_dptr->pageUp();    endResetModel();}int DynamicListModel::pageSize(){    return m_dptr->m_pageSize;}void DynamicListModel::setPageSize(int size){    m_dptr->m_pageSize = size;    m_dptr->adjustPageRange();    emit pageSizeChanged(size);}int DynamicListModel::total(){   return m_dptr->m_total;}void DynamicListModel::setTotal(int total){    m_dptr->m_total = total;    m_dptr->adjustPageRange();    emit totalChanged(total);}

Dynamiclistmodel only demonstrates usage. It uses four integer variables: m_start, m_end, m_total, and m_pagesize to simulate actual data. The data () method is used to convert the row serial number in the listview with m_start into a string and return the result. The text is displayed on the listview interface.

The loadmore () function is used to distinguish whether to load data forward or backward. It calls the Pagedown () and Pageup () functions of dynamiclistmodel to update the internal data status. At the beginning of loadmore (), call beginresetmodel () to notify the view associated with dynamiclistmodel to refresh themselves. When the internal data status update ends, call endresetmodel () to notify the view, in this way, the view will refresh and finally call the data () method to prepare the data when instantiating the item delegate. At this time, m_start has changed, so the numbers displayed on the interface have also changed.

Export C ++ Model

This is simple. We have already discussed it in the article "qml of QT quick and C ++ mixed programming details. Directly look at main. cpp:

#include <QGuiApplication>#include <QQmlApplicationEngine>#include <QQmlContext>#include "dynamicModel.h"int main(int argc, char *argv[]){    QGuiApplication app(argc, argv);    QQmlApplicationEngine engine;    QQmlContext *ctx = engine.rootContext();    ctx->setContextProperty("dynamicModel", new DynamicListModel());    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));    return app.exec();}

Qml code Introduction

It's time to look at main. qml:

import QtQuick 2.2import QtQuick.Window 2.1import QtQuick.Controls 1.2import QtQuick.Layouts 1.1import QtQuick.Controls.Styles 1.2Window {    width: 320;    height: 480;    minimumWidth: 300;    minimumHeight: 480;    visible: true;    id: root;    Component {        id: listDelegate;        Text {            id: wrapper;            width: parent.width;            height: 32;            font.pointSize: 15;            verticalAlignment: Text.AlignVCenter;            horizontalAlignment: Text.AlignHCenter;            text: content;            color: ListView.view.currentIndex == index ? "red" : "blue";            MouseArea {                anchors.fill: parent;                onClicked: {                    if(wrapper.ListView.view.currentIndex != index){                        wrapper.ListView.view.currentIndex = index;                    }                }            }        }    }    ListView {        id: dynamicList;        z: 1;        anchors.fill: parent;        anchors.margins: 10;        delegate: listDelegate;        model: dynamicModel;        focus: true;        activeFocusOnTab: true;        highlight: Rectangle {            color: "steelblue";        }        property real contentYOnFlickStarted: 0;        onFlickStarted: {            //console.log("start,origY - ", originY, " contentY - ", contentY);            contentYOnFlickStarted = contentY;        }        onFlickEnded: {            //console.log("end,origY - ", originY, " contentY - ", contentY);            dynamicModel.loadMore(contentY < contentYOnFlickStarted);        }    }}

When defining a listview object, specify its model as the dynamicmodel exported from the main () function. Do not elaborate on other code. Let's just look at the key code that implements pull-down (pull-up) Refresh.

Here, we only record the contenty at the beginning of flick to the contentyonflickstarted attribute.

Here we compare the contenty at the end of flick with the contenty at the start (I .e., contentyonflickstarted). If the end is small, it indicates that it is a drop-down command. If the end is large, it indicates that it is a pull-up command. Call loadmore () based on the comparison result ().

Okay, that's easy. Check the effect.

Pull-down refresh Effect

Figure 1 shows the initial effect:


Figure 1 initial effect of Dynamic Refresh list

Figure 2 shows the effect after two drop-down operations:


Figure 2 effect after pull-down and refresh

Figure 3 shows the effect of pulling from the status shown in Figure 2:


Figure 3 pull-up effect


All rights reserved foruok. For more information, see http://blog.csdn.net/foruok.

Okay. The explanation is complete.

Review this series of articles:

  • Qt quick introduction
  • Qml language basics
  • Qt Quick's hello World graphic explanation
  • Simple QT quick tutorial
  • Signal and slot of QT quick event processing
  • Qt quick event processing-mouse, keyboard, and Timer
  • Qt quick event processing-pinch, zoom, and rotate
  • Dynamic Creation of QT quick components and objects
  • Introduction to QT quick Layout
  • Qml and C ++ mixed programming in QT quick
  • Qt quick image processing instance meitu xiuxiu (source code download)
  • Explanation of QT quick pathview
  • Picture digging for Qt quick instances
  • Qt quick integrated instance File Viewer

Qt quick listview pull-down to refresh data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.