Qt ListView使用

article/2025/9/26 9:47:42

概述

Qt中ListView加载数据一般有两种方式,一种是直接qml文件中model直接定义并且放置数据,一种是C++代码中定义Model,再setContextProperty的方式暴露给qml域。
官方介绍

步骤

(1)qml界面

import QtQuick 2.0
import QtQuick.Controls 1.5
import QtQuick.Controls.Styles 1.4
import QtQuick.Layouts 1.3
SubPageForm {title:"切换线路"property int font_mid_size:24bodyArea:  Rectangle {id: subrootcolor: "#00ffffff"Image {id: tablebgsource: "../Resources/tablebg.jpg"anchors.left: parent.leftanchors.leftMargin: 50anchors.right: parent.rightanchors.rightMargin: 50anchors.top: parent.topanchors.topMargin: 30ListView {id: datalistanchors.fill: parentinteractive:falseheader:Rectangle{width: datalist.widthheight: 53color:Qt.rgba(0,0,0,0)RowLayout{anchors.left: parent.leftanchors.right: parent.rightheight: parent.heightText{text:"序号"color:"white"font.pixelSize:font_mid_sizehorizontalAlignment: Text.AlignHCenterLayout.fillWidth:true}Text{text:"线路"color:"white"font.pixelSize:font_mid_sizehorizontalAlignment: Text.AlignHCenterLayout.fillWidth:true}Text{text:"方向"color:"white"font.pixelSize:font_mid_sizehorizontalAlignment: Text.AlignHCenterLayout.fillWidth:true}}}delegate:Rectangle{width: datalist.widthheight: 53color:Qt.rgba(0,0,0,0)RowLayout{anchors.left: parent.leftanchors.right: parent.rightheight: parent.heightText{text:PosRolecolor:"white"font.pixelSize:font_mid_sizehorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenterLayout.fillWidth:trueLayout.preferredWidth:100}Text{text:LineRolecolor:"white"font.pixelSize:font_mid_sizehorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenterLayout.fillWidth:trueLayout.preferredWidth:100}Text{text:DirectRolecolor:"white"font.pixelSize:font_mid_sizehorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenterLayout.fillWidth:trueLayout.preferredWidth:100}}}model:LineInfoModel}Component.onCompleted: {LineInfoModel.refresh()}}RowLayout {anchors.left: tablebg.leftanchors.right: tablebg.rightanchors.leftMargin: 10anchors.rightMargin: 10anchors.bottom: parent.bottomanchors.bottomMargin: 10Text {id: footertexttext: qsTr("当前第")+LineInfoModel.curpage+qsTr("页 , 共")+LineInfoModel.totalpage+qsTr("页")+qsTr(" 数量")+LineInfoModel.linenumLayout.preferredHeight: 42Layout.preferredWidth: 560font.pixelSize: font_mid_sizecolor:"white"}NormalButton {id: previouspageLayout.preferredHeight: 35Layout.preferredWidth: 35imgsource:pressed? "qrc:/Resources/up_click.bmp":"qrc:/Resources/up.bmp"onClicked: {LineInfoModel.jumptoPrevious();}}NormalButton {id: nextpageLayout.preferredHeight: 35Layout.preferredWidth: 35imgsource: pressed? "qrc:/Resources/down_click.bmp":"qrc:/Resources/down.bmp"onClicked: {LineInfoModel.jumptoNext();}}}}}

(2)自定义Model类(继承QAbstractListModel)

#ifndef LINEINFOMODEL_H
#define LINEINFOMODEL_H#include<QAbstractListModel>
class Line_Element
{
public:Line_Element(int pos,QString line ,QString direct){m_pos = pos;m_line = line;m_direct = direct;}int getPos()const{ return m_pos;}QString getLine() const{return m_line;}QString getDirect() const{return m_direct;}
private:int m_pos;QString m_line;QString m_direct;
};class LineInfoModel : public QAbstractListModel
{Q_PROPERTY(int curpage READ getCurpage WRITE setCurpage NOTIFY curpageChanged)Q_PROPERTY(int totalpage READ getTotalpage WRITE setTotalpage NOTIFY totalpageChanged)Q_PROPERTY(int linenum READ getLineNum WRITE setLineNum NOTIFY linenumChanged)Q_OBJECT
public:LineInfoModel();enum LineInfo_Roles{PosRole =Qt::UserRole + 1,LineRole,DirectRole};int rowCount(const QModelIndex & parent = QModelIndex()) const;QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;QHash<int, QByteArray> roleNames() const;void addLine(int pos,QString line,QString direct);void setLines(const QList<Line_Element>& list);int getCurpage(){return m_curpage;}void setCurpage(int val){m_curpage = val; emit curpageChanged();}int getTotalpage(){return m_totalpage;}void setTotalpage(int val){m_totalpage = val;emit totalpageChanged();}int getLineNum(){return m_linenum;}void setLineNum(int val){m_linenum = val;emit linenumChanged();}void RefreshDisplay();
public slots:void jumptoPrevious();void jumptoNext();void refresh(){RefreshDisplay();};
signals:void curpageChanged();void totalpageChanged();void linenumChanged();
private:QList<Line_Element> m_display_list;QList<Line_Element> m_line_list;int m_curpage = 0;int m_totalpage = 0;int m_linenum = 0;//amount of lines
};#endif // LINEINFOMODEL_H
#include "LineInfoModel.h"
#include<QDebug>
LineInfoModel::LineInfoModel()
{m_curpage=0;m_totalpage=0;m_linenum=0;
}/*** @brief LineInfoModel::addLine 添加一条数据* @param pos* @param line* @param direct*/
void LineInfoModel::addLine(int pos, QString line, QString direct)
{Line_Element ele(pos,line,direct);m_line_list.append(ele);int _line_num = m_line_list.count();setCurpage(1);setTotalpage(_line_num/5+1);setLineNum(_line_num);
}
/*** @brief LineInfoModel::setLines 设置 List* @param list*/
void LineInfoModel::setLines(const QList<Line_Element> &list)
{m_line_list.clear();m_line_list = list;int _line_num = m_line_list.count();qDebug()<<"line num = "<<_line_num;if(_line_num>0){setCurpage(1);setTotalpage(_line_num/5+1);setLineNum(_line_num);m_display_list.clear();for(int i=0;i<m_line_list.count();i++){m_display_list<<m_line_list.at(i);}}
}/*** @brief LineInfoModel::jumptoPrevious 上一页*/
void LineInfoModel::jumptoPrevious()
{if(m_curpage<=1){return;}setCurpage(m_curpage-1);RefreshDisplay();
}/*** @brief LineInfoModel::jumptoNext 下一页*/
void LineInfoModel::jumptoNext()
{if(m_curpage>=m_totalpage){return;}setCurpage(m_curpage+1);RefreshDisplay();
}/*** @brief LineInfoModel::RefreshDisplay 刷新页面*/
void LineInfoModel::RefreshDisplay()
{beginRemoveRows(QModelIndex(),0,m_display_list.count());m_display_list.clear();endRemoveRows();int num=0;if(m_curpage<m_totalpage){num=5;}else{num = m_linenum%5;}beginInsertRows(QModelIndex(),0,num);for(int i=0;i<num;i++){int _index = (m_curpage-1)*5+i;m_display_list<<m_line_list.at(_index);}endInsertRows();
}/*** @brief LineInfoModel::roleNames 返回模型的属性名称。继承自父类。* @return*/
QHash<int, QByteArray> LineInfoModel::roleNames() const
{QHash<int, QByteArray> roles;roles[PosRole] = "PosRole";roles[LineRole] = "LineRole";roles[DirectRole]= "DirectRole";return roles;
}/*** @brief LineInfoModel::rowCount 返回模型的行数,此函数会在需要指导模型行数的时候被自动调用* @param parent* @return*/
int LineInfoModel::rowCount(const QModelIndex &parent) const
{return m_display_list.count();
}/*** @brief LineInfoModel::data 返回数据* @param index 需要的数据的序号* @param role 需要的数据的角色* @return*/
QVariant LineInfoModel::data(const QModelIndex &index, int role) const
{Line_Element ele = m_display_list.at(index.row());switch(role){case PosRole:{return ele.getPos();}case LineRole:{return ele.getLine();}case DirectRole:{return ele.getDirect();}}
}

这里主要实现三个方法:
<1>int rowCount(const QModelIndex & parent = QModelIndex()) const;
这里写图片描述

<2>QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
这里写图片描述

<3>QHash< int, QByteArray> roleNames() const;
这里写图片描述

(3)暴露自定义Model给qml域

context->setContextProperty("LineInfoModel",&msg.m_lineinfo_model);

上下文属性可以存储为QVariant或者QObject*类型.这意味着自定义的C++对象也可以使用这种方式注入,而且可以直接在QML中读取或修改这些对象.我们将上例中的QDateTime值修改为一个嵌入的QObject实例,让QML代码调用对象实例的方法


http://chatgpt.dhexx.cn/article/h5TBqAjI.shtml

相关文章

Android控件listview ListView的用法

在Android开发中&#xff0c;ListView是一个比较常用的控件&#xff0c;它以列表的形式展示数据内容&#xff0c;并且能够根据列表的高度自适应屏幕显示。ListView的样式是由属性决定的&#xff0c;它的常用属性如下所示 android:listSelector 点击后改变背景颜色 android:divi…

Android之ListView实现

ListView 用来显示多个可滑动项&#xff08;Item&#xff09;列表的ViewGroup。 需要使用Adapter&#xff08;适配器&#xff09;将集合数据和每一个Item所对应的布局动态适配到ListView中显示 显示列表&#xff1a;listView.setAdapter(adapter) Adapter ArrayAdapter&#xf…

ListView使用方法

ListView使用方法总结 - 直接使用ListView组件创建列表 - 通过Activity继承ListActivity创建 - 定制ListView界面 直接使用ListView组件创建列表 通过数组资源文件指定列表项 先在XML布局文件中添加ListView标志&#xff0c;设置好相关属性&#xff1b;在values下创建数组资…

Android—— ListView 的简单用法及定制ListView界面

一、ListView的简单用法 2. 训练目标 1) 掌握 ListView 控件的使用 2) 掌握 Adapter 桥梁的作用 实现步骤&#xff1a; 1&#xff09;首先新建一个项目&#xff0c; 并让ADT 自动帮我们创建好活动。然后修改activity_main.xml 中的代码&#xff0c;如下所示&#xff1a; &…

QT listView学习

文章目录 listViewdemo说明demo演示model定义委托 QStyledItemDelegate总结 listView listView 对比 tableView 、 treeView来说&#xff0c;最大的不同就是数据结构的不同。treeView是像树一样的层次结构&#xff0c;而listView则就是像链表一样的结构 跟之前的treeView&…

还在用ListView?

还在用Lisview&#xff1f;RecyclerView都已经出来一年多了&#xff01; 想必大家多或多或少的接触过或者了解过RecyclerView&#xff0c;为什么没有用起来&#xff0c;原因大概如下&#xff1f; ListView我用的挺好的&#xff0c;为什么要换RecyclerView&#xff1f;ListView…

ListView用法

ListView是用于显示数据的&#xff0c;先在窗体中拉一个lisview控件&#xff0c;还有一些新增、修改、删除、查询按钮和文本框&#xff0c;控件名称为listview,按钮为btnInsert,btnUpate,btnDeleteOne,btnDelete,btnSelect,文本框的名称为txtName,txtSex,txtPhone,txtAddress,设…

ListView的基础用法

最近学到ListView和RecyclerView&#xff0c;感觉有点难理解&#xff0c;于是自己找到了篇文章&#xff0c;感觉写的挺详细的&#xff08;文章链接在文末&#xff09;&#xff0c;然后自己再整理敲了跑了一遍&#xff0c;总结了一下&#xff0c;方便自己以后回头温习。 一个Li…

Android(14) ArrayAdapter(数组适配器)的三种方法

ArrayAdapter数组适配器用于绑定格式单一的数据&#xff0c;数据源可以是集合或者数组 列表视图(ListView)以垂直的形式列出需要显示的列表项。 实现过程&#xff1a;新建适配器->添加数据源到适配器->视图加载适配器 第一种&#xff1a;直接用ListView组件创建 列表…

Android——列表视图(ListView)

1、什么是ListView&#xff1f;它可以实现怎样的功能&#xff1f; 列表视图是android中最常用的一种视图组件&#xff0c;它以垂直列表的形式列出需要显示的列表项。手机屏幕空间有限&#xff0c;能显示的内容不多。可以借助ListView来显示更多、更丰富的内容。ListView允许用…

ListView详细介绍与使用

前言介绍&#xff1a; 关于 ListView 我们大家都应该是非常的熟悉了&#xff0c;在 Android 开发中是经常用到的&#xff0c;今天就再来回顾一下&#xff0c;ListView 的使用方法&#xff0c;和一些需要优化注意的地方&#xff0c;还有日常开发过程中的一些小技巧和经验。 Li…

Android最常用的控件ListView(详解)

一.ListView简介 在Android开发中&#xff0c;ListView是一个比较常用的控件。它以列表的形式 展示具体数据内容&#xff0c;并且能够根据数据的长度自适应屏幕显示。 二.ListView简单用法 代码部分 1.布局界面 activity_main.xml 代码&#xff1a; <?xml version"1…

ListView的用法

一、 ListView的使用 <ListView>:用于展示大量数据的一种列表视图,通过上下滑动的方式将屏幕外的数据滚动到屏幕内。 数据无法直接传递给ListView,需要适配器 Adapter:作用是将各种数据以合适的形式展示到View上 实例&#xff1a; Food.java: public class Food {priv…

Android原生AlertDialog修改标题,内容,按钮颜色,字体大小等

private void showAlerDialog() {AlertDialog dialog new AlertDialog.Builder(this).setTitle("AlerDialog").setMessage("这是一个AlertDialog").setPositiveButton("确定",null).setNegativeButton("取消",null).create();dialog.…

【android学习】Dialog对话框

1&#xff0c;Dialog 1&#xff09;onCreateDialog(int) 2&#xff09;showDialog(int) 第一次请求时&#xff0c;会从Activity中调用onCreateDialog。 3&#xff09;onPrepareDialog(int,Dialog) 在每次打开对话框时被调用。 4&#xff09;dismissDialog(int) 关闭对话…

Android Dialog使用详解

对话框是提示用户作出决定或输入额外信息的小窗口&#xff0c;通常不会填充整个屏幕&#xff0c;用于进行一些额外交互 Dialog 类是对话框的基类&#xff0c;但应该避免直接实例化 Dialog&#xff0c;而应使用其子类&#xff0c;比如 AlertDialog 此对话框可显示标题、提示信…

Android 修改AlertDialog原生setPositiveButton的字体颜色背景颜色大小边距位置

看效果图&#xff1a; public void lanyaClick(View v) {//点击确定之后转向登陆框LayoutInflater factory LayoutInflater.from(Beforestart.this);//得到自定义对话框final View DialogView factory.inflate(R.layout.item_alert_dialog, null);//创建对话框android.app.Al…

setPositiveButton和setNegativeButton的区别

setPositiveButton和setNegativeButton的区别和setNeutralButton的区别 三者都是AlertDialog弹出框的按钮&#xff0c;都是封装好的button&#xff0c;只是显示的位置不同&#xff0c;项目中可根据情况选择使用&#xff0c;setNegativeButton一般用于确认&#xff0c;setNegat…

GPS(rinex格式)数据解析详细解读

RINEX格式现如今已成为GPS测量应用中的标准数据格式&#xff0c;目前应用最为广泛、最普遍的是RINEX格式的第2个版本&#xff0c;该版本能够用于包括静态和动态GPS测量在内的不同观测模式数据。在该版本中定义了6种不同类型的数据文件&#xff0c;分别用于存放不同类型的数据&a…

2020/10/23 GPS的数据格式学习

GPS的数据格式学习 一、在使用GPS的通过串口向电脑发送数据的时候&#xff0c;要注意GPS数据线的连接&#xff1b; 1.1 VCC接VCC&#xff1b;&#xff08;VCC表示接电源正极&#xff09; 1.2 GND接GND&#xff1b;&#xff08;GND表示接地或接电源负极&#xff09; 1.3 TX接RX…