qml 实现一个listview

主要通过qml实现listvie功能,主要包括右键菜单,滚动条,拖动改变内容等,c++ 与 qml之间的变量和函数的调用。

main.cpp

#include <QQuickItem>
#include <QQmlContext>
#include "testlistmodel.h"
int main(int argc, char *argv[])
{QGuiApplication app(argc, argv);QQmlApplicationEngine engine;qmlRegisterType<TestListModel>("TestListModel", 1, 0, "TestListModel");engine.load(QUrl(QStringLiteral("qrc:/ui1.qml")));QObject* root = engine.rootObjects().first();QString retVal;QVariant message = "Hello from c++";QVariant returnedValue;QQmlProperty(root,"testmsg").write("hello,world");qDebug()<<"Cpp get qml property height222"<<root->property("msg");bool ret =QMetaObject::invokeMethod(root,"setSignalB",Q_RETURN_ARG(QVariant,returnedValue),Q_ARG(QVariant,message),Q_ARG(QVariant,8));qDebug()<<"returnedValue"<<returnedValue<<root<<ret;return app.exec();
}

listview 的model 代码

TestListModel.h

#ifndef TESTLISTMODEL_H
#define TESTLISTMODEL_H#include <QAbstractListModel>
typedef struct Student
{int     id;QString name;QString sex;
}pStudent;class TestListModel : public QAbstractListModel
{Q_OBJECT
public:explicit TestListModel(QObject *parent = nullptr);int rowCount(const QModelIndex &parent) const;QVariant data(const QModelIndex &index, int role) const;virtual QHash<int, QByteArray> roleNames() const;Qt::ItemFlags flags(const QModelIndex &index) const override;Q_INVOKABLE void modifyItemText(int row1,int row2);Q_INVOKABLE void add();enum MyType{ID=Qt::UserRole+1,Name,Sex};
private:QVector<Student>  m_studentList;signals:void    layoutChanged();
};#endif // TESTLISTMODEL_H

TestListModel.cpp

#include "testlistmodel.h"
#include <QDebug>TestListModel::TestListModel(QObject *parent): QAbstractListModel{parent}
{for(int i=0;i<20;i++){Student oneData;oneData.id = i;oneData.name  = QString("张三%1").arg(i);if(i%2==0){oneData.sex = "female" ;}else{oneData.sex = "male" ;}//qDebug()<<"TestListModel"<<m_studentList.size();m_studentList.append(oneData);}   }int TestListModel::rowCount(const QModelIndex &parent) const
{//qDebug()<<"rowCount"<<m_studentList.size();return m_studentList.size();
}
QVariant TestListModel::data(const QModelIndex &index, int role) const
{// qDebug()<<"TestListModel::data11111111111"<<index.isValid();QVariant var;if ( !index.isValid() ){return QVariant();}int nRow    = index.row();int nColumn = index.column();if(Qt::UserRole+1 == role){var = QVariant::fromValue(m_studentList.at(nRow).id);}else if(Qt::UserRole+2 == role){var = QVariant::fromValue(m_studentList.at(nRow).name);// qDebug()<<"m_listData.at(nRow).name"<<m_listData.at(nRow).name;}else if(Qt::UserRole+3 == role){var = QVariant::fromValue(m_studentList.at(nRow).sex);// qDebug()<<"m_listData.at(nRow).name"<<m_listData.at(nRow).name;}return var;
}QHash<int, QByteArray> TestListModel::roleNames() const
{QHash<int, QByteArray> d;d[MyType::ID]="id";d[MyType::Name]="name";d[MyType::Sex]="sex";qDebug()<<"d .size"<<d.size();return d;
}
Qt::ItemFlags TestListModel::flags(const QModelIndex &index) const
{Q_UNUSED(index)// if(index.column() ==1)// {//     qDebug()<<"UserInfoModel::flags  1111";//     return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;// }qDebug()<<"TestListModel::flags";return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}void TestListModel::modifyItemText(int row1, int row2)
{m_studentList.swapItemsAt(row1,row2);beginResetModel();endResetModel();
}void TestListModel::add()
{Student student;student.id   = 123;student.name = "love";student.sex  = "man";m_studentList.push_back(student);beginResetModel();endResetModel();emit layoutChanged();}

ui.qml

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Layouts 1.2
import TestListModel 1.0import QtQuick 2.12import QtQuick 2.2
import QtQml.Models 2.2
//import QtQuick.Controls 2.12
//QtQuick.Controls 2.12  和QtQuick.Controls.Styles 1.4不匹配
import QtQuick.Controls.Styles 1.4
import QtQuick.Controls 1.4
import QtQuick.Controls 2.12
import QtLocation 5.15
//import "CustomMenuItem.qml"
// import QtQuick.Controls 2.15//import QtQuick.Controls 2.5Window {id:window//anchors.centerIn: parentwidth: 650;height: 457visible: trueflags: Qt.FramelessWindowHint | Qt.Dialogproperty string testmsg: "GongJianBo1992"Rectangle{id:rect1;anchors.fill: parent;border.width: 1;color: "transparent";border.color: "red";clip:true//这一属性设置表示如果他的子类超出了范围,那么就剪切掉,不让他显示和起作用}//无边框移动MouseArea {id: dragRegionanchors.fill: parentproperty point clickPos: "0,0"onPressed: {clickPos = Qt.point(mouse.x,mouse.y)}onReleased: {clickPos = Qt.point(0,0)}onPositionChanged: {//鼠标偏移量var delta = Qt.point(mouse.x-clickPos.x, mouse.y-clickPos.y)//如果mainwindow继承自QWidget,用setPoswindow.setX(window.x+delta.x)window.setY(window.y+delta.y)}} Menu {id: contextMenubackground: Rectangle {// @disable-check M16anchors.fill:parentimplicitWidth: 200implicitHeight: 30color: "lightblue"}Action{id:no1text:"123"onTriggered:{console.log("选项一被点击")tableView.selectAllItem()}// @disable-check M16}Menu{background: Rectangle {// @disable-check M16anchors.fill:parentimplicitWidth: 200implicitHeight: 30color: "lightblue"}title:"love"Action{id:no4text:"789"onTriggered:{console.log("选项六被点击")tableView.selectAllItem()}}}Action {id:no2text:"234"onTriggered:{console.log("选项二被点击")tableView.disselectAllItem()}}MenuSeparator {contentItem: Rectangle {// @disable-check M16implicitWidth: 200implicitHeight: 1color: "#21be2b"}}Action {id:no3text:"345"onTriggered: console.log("选项三被点击")}delegate: MenuItem {// @disable-check M16id: menuItemheight: 40// @disable-check M16contentItem: Text{// @disable-check M16text:menuItem.textcolor: menuItem.highlighted? "gary": "blue"}background: Rectangle{// @disable-check M16implicitWidth: 200implicitHeight: 30color: menuItem.highlighted? "purple":"lightblue"}arrow: Image {// @disable-check M16id: arrowImagex: parent.width - widthy: parent.height/2 -height/2visible: menuItem.subMenusource: "qrc:/Right arrow.png"}}}TestListModel{id: myModeonLayoutChanged:{console.log("LayoutChanged")}}// Page{//    x:listwidget.x//    y:listwidget.y//    width:  listwidget.width//    height: listwidget.height//    background: Rectangle{//        anchors.fill: parent//        color: "white"//        border.width: 1//        border.color: "black"//    }// }Rectangle{width:  window.width-60+2height: 300+2border.color: "lightgreen"border.width: 1color: "transparent"x:30y:40ListView {id: listwidgetwidth:  parent.width-2//window.width-60height: parent.height-2//   300x:1y:1interactive: false // @disable-check M16model: myModeclip: true  //不写的话,滚动的时候,listview会有拖拽的感觉//orientation: ListView.Vertical //垂直列表        ScrollBar.vertical: ScrollBar {id: scrollBarhoverEnabled: trueactive: hovered || pressedpolicy: ScrollBar.AlwaysOnorientation: Qt.Verticalsize: 0.8anchors.top: parent.topanchors.right: parent.rightanchors.bottom: parent.bottomcontentItem: Rectangle  {implicitWidth: 6  //没指定的时候的宽度implicitHeight: 100 //没有指定高度的时候radius: width / 2color: scrollBar.pressed ? "#81e889" : "#c2f4c6"}}Rectangle{id : dargRectwidth: 100height: 30visible: falsecolor: "lightgray";Text {anchors.verticalCenter: parent.verticalCenteranchors.horizontalCenter: parent.horizontalCenterid: dargRectText// text: "123"horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter}}delegate: Item{id:itemDrag1width: window.width-60height: 30property int dragItemIndex: 0property bool isHover: falseRectangle {width: window.width-60height: 30//radius: 5;// border.width: 1// border.color: "white"color:isHover === true? "lightgreen":listwidget.currentIndex === index ? "lightblue" : "gray"Text {id:itemDrag2anchors.verticalCenter: parent.verticalCenteranchors.left: parent.left// text: "123"horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCentertext: id+":"+name+":"+sex}                MouseArea {id: mouseAreaanchors.fill: parentacceptedButtons: Qt.LeftButton | Qt.RightButtonhoverEnabled: trueonWheel: {// @disable-check M16// 当滚轮被滚动时调用// 事件参数wheel提供了滚动的方向和距离if (wheel.angleDelta.y > 0) {//console.log("向上滚动")scrollBar.decrease();}else {//console.log("向下滚动")scrollBar.increase();}}onEntered:{isHover = true//console.log("onEntered" +isHover)}onExited:{isHover = false//console.log("onExited" +isHover)}onClicked:{if (mouse.button === Qt.RightButton)//菜单{console.log("menu RightButton")contextMenu.popup()}else{//var other_index = listwidget.indexAt(mouseArea.mouseX , mouseArea.mouseY );listwidget.currentIndex = index // 点击时设置当前索引为该项的索引值dragItemIndex = index;console.log("onClicked"+index)}}onPressAndHold:  {if(mouse.button === Qt.LeftButton){console.log("onPressAndHold"+index)listwidget.currentIndex = indexdargRect.x = mouseX +itemDrag1.xdargRect.y = mouseY+itemDrag1.ydragItemIndex = index;dargRectText.text = itemDrag2.textdargRect.visible = true}}onReleased:{if(dargRect.visible === true){dargRect.visible = falsevar other_index = listwidget.indexAt(mouseX +itemDrag1.x , mouseY+itemDrag1.y );console.log("onReleased"+other_index)if(dragItemIndex!==other_index){var afterItem   = listwidget.itemAtIndex(other_index );// listwidget.myModel.get(other_index).textmyModel.modifyItemText(dragItemIndex,other_index)//console.log("onReleased"+myModel)}}}onPositionChanged:{//console.log("onPositionChanged111" + mouse.button)if(mouse.button === Qt.LeftButton){//console.log("onPositionChanged222")var other_index = listwidget.indexAt(mouseX +itemDrag1.x , mouseY+itemDrag1.y );listwidget.currentIndex  = other_index;dargRect.x = mouseX +itemDrag1.xdargRect.y = mouseY+itemDrag1.y}}                     }}}}}Button {id: button1x: parent.width-80y: parent.height-36width:70height:30//text: qsTr("Button")background:Rectangle // @disable-check M16{//anchors.fill: parentborder.color: "royalblue"border.width: 1color: button1.down ? "red" :(button1.hovered?"blue":"lightsteelblue")}Text {text: "1213";// anchors.fill: parentanchors.centerIn: parent;color: button1.hovered?"yellow":"red";font.pixelSize: 13;//font.weight: Font.DemiBold}       Connections {target: button1function onClicked(){window.close();}}}function myQmlFunction( msg,index) {console.log("Got message:", msg)return "some return value"}function setSignalB(name, value){console.log("setPoint"+" "+testmsg);console.log("qml function processB",name,value);myMode.add();return value}}

运行结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1483551.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

Haproy服务

目录 一.haproxy介绍 1.主要特点和功能 2.haproxy 调度算法 3.haproxy 与nginx 和lvs的区别 二.安装 haproxy 服务 1. yum安装 2.第三方rpm 安装 3.编译安装haproxy 三.配置文件详解 1.官方地址配置文件官方帮助文档 2.HAProxy 的配置文件haproxy.cfg由两大部分组成&…

什么是正则表达式,如何在 Python 中使用?

什么是正则表达式 正则表达式&#xff08;Regular Expression&#xff0c;简称Regex&#xff09;是一种用于匹配字符串中字符模式的工具。它是由普通字符&#xff08;例如字母、数字&#xff09;以及一些特殊字符&#xff08;称为元字符&#xff09;组成的字符序列。这种模式用…

FastAPI 学习之路(六十)打造系统的日志输出

我们要搭建日志系统&#xff0c;可以使用loguru&#xff0c;很不错的一个开源日志系统 pip install loguru 我们在common创建log.py&#xff0c;使用方式也很简单 import os import timefrom loguru import logger# 日志的路径 log_path os.path.join(os.getcwd(), "log…

【electron】 快速启动electron 应用

学无止境&#xff1a; 最近在搞electron项目&#xff0c;最重要的是总结 &#xff0c;写下来总不会忘记&#xff0c;也希望给大家参考一下&#xff0c;有不对的地方希望大家多指点。 快速启动electron 应用 1 克隆示例项目的仓库 git clone https://github.com/electron/ele…

PCB(印制电路板)制造涉及的常规设备

印制电路板&#xff08;PCB&#xff09;的制造涉及多种设备和工艺。从设计、制作原型到批量生产&#xff0c;每个阶段都需要不同的专业设备。以下是一些在PCB制造过程中常见的设备&#xff1a; 1. 计算机辅助设计&#xff08;CAD&#xff09;软件&#xff1a; - 用于设计PC…

又缩水Unity7月闪促限时4折活动模块化角色模板编辑器场景美术插件拖尾怪物3D模型UI载具AI对话TPS飞机RPG和FPS202407

Flash Deals are Coming Back! 限时抢购又回来了&#xff01; July 17, 2024 8:00:00 PT to July 24, 2024 7:59:00 PT 太平洋时间 2024 年 7 月 17 日 8&#xff1a;00&#xff1a;00 至 2024 年 7 月 24 日 7&#xff1a;59&#xff1a;00&#xff08;太平洋时间&#xff09;…

模块化沙箱:解锁数据防泄密的终极密码

在这个数字化时代&#xff0c;数据已经成为企业最宝贵的资产之一。然而&#xff0c;数据泄露的威胁如同暗夜中的幽灵&#xff0c;随时可能侵袭企业的信息安全防线。面对日益复杂的内外部风险&#xff0c;企业亟需一种既高效又灵活的安全解决方案&#xff0c;来保护其核心数据不…

Linux编辑器——vim的使用

目录 vim的基本概念 命令模式 底行模式 插入模式 注释和取消注释 普通用户进行sudo提权 vim配置问题 vim的基本概念 一般使用的vim有三种模式&#xff1a; 命令模式 底行模式和插入模式&#xff0c;可以进行转换&#xff1b; vim filename 打开vim&#xff0c;进入的…

【.NET全栈】ASP.NET开发Web应用——AJAX开发技术

文章目录 前言一、ASP.NET AJAX基础1、AJAX技术简介2、ASP.NET AJAX技术架构 二、ASP.NET AJAX服务器端扩展1、声明ScriptManager控件2、使用ScriptManager分发自定义脚本3、在ScriptManager中注册Web服务4、处理ScriptManager中的异常5、编程控制ScriptManager控件6、使用Upda…

【论文解读】VoxelNeXt: Fully Sparse VoxelNet for 3D Object Detection and Tracking

VoxelNeXt 摘要引言方法Sparse CNN Backbone AdaptationSparse Prediction Head 3D Tracking实验结论 摘要 3D物体检测器通常依赖于手工制作的方法&#xff0c;例如锚点或中心&#xff0c;并将经过充分学习的2D框架转换为3D。因此&#xff0c;稀疏体素特征需要通过密集预测头进…

分布式搜索引擎ES-Elasticsearch进阶

1.head与postman基于索引的操作 引入概念&#xff1a; 集群健康&#xff1a; green 所有的主分片和副本分片都正常运行。你的集群是100%可用 yellow 所有的主分片都正常运行&#xff0c;但不是所有的副本分片都正常运行。 red 有主分片没能正常运行。 查询es集群健康状态&…

Java流的概念及API

流的概念 流&#xff08;Stream)的概念代表的是程序中数据的流通&#xff0c;数据流是一串连续不断的数据的集合。在Java程序中&#xff0c;对于数据的输入/输出操作是以流(Stream)的方式进行的。可以把流分为输入流和输出流两种。程序从输入流读取数据&#xff0c;向输出流写入…

曲轴自动平衡机:提升制造精度与效率的利器

在现代制造业中&#xff0c;曲轴作为发动机的核心部件之一&#xff0c;其质量和性能直接影响着整个发动机的运行效果。而曲轴自动平衡机的出现&#xff0c;为曲轴的生产制造带来了显著的优势。 一、高精度平衡校正 曲轴自动平衡机采用先进的传感技术和精密的测量系统&#xff0…

【TortoiseGitPlink提示输入密码解决方法】

问题&#xff1a;TortoiseGitPlink提示输入密码 解决方案 参考链接&#xff1a;TortoiseGitPlink提示输入密码解决方法 但后半部分和上文不同&#xff0c;点击图中 Load Putty Key 即可。

基于FPGA的多路选择器

目录 一、组合逻辑 二、多路选择器简介&#xff1a; 三、实战演练 摘要&#xff1a;本实验设计并实现了一个简单的多路选择器&#xff0c;文章后附工程代码 一、组合逻辑 组合逻辑是VerilogHDL设计中的一个重要组成部分。从电路本质上讲&#xff0c;组合逻辑电路的特点是输…

MathType加载项被word禁用怎么办 MathType加载到Word不能用

Word中的MathType加载项是指将MathType软件与Word文档进行关联的一项功能。它允许用户在Word中直接使用MathType的功能&#xff0c;方便地输入和编辑数学公式等内容。通过加载项&#xff0c;MathType的强大数学公式编辑能力可以与Word的文档处理功能相结合&#xff0c;提高工作…

ELK 8.14版本搭建

1.架构图 2.基础环境准备&#xff1a; 2.1 关闭防火墙和selinux [rootlocalhost ~]# setenforce 0 [rootlocalhost ~]# sed -i s/SELINUXenforcing/SELINUXdisabled/g /etc/selinux/config [rootlocalhost ~]# cat /etc/selinux/config # This file controls the state of SEL…

【Django】网上蛋糕商城后台-类目管理

1.类目管理列表实现 当管理员进入后台管理后&#xff0c;点击类目管理&#xff0c;向服务器发出请求 path(admin/type_list/,viewsAdmin.type_list), # 处理商品分类管理列表请求 def type_list(request):# 读取分页页码try:ym request.GET["ym"]except:ym 1# 查…

专业PDF编辑工具:Acrobat Pro DC 2024.002.20933绿色版,提升你的工作效率!

软件介绍 Adobe Acrobat Pro DC 2024绿色便携版是一款功能强大的PDF编辑和转换软件&#xff0c;由Adobe公司推出。它是Acrobat XI系列的后续产品&#xff0c;提供了全新的用户界面和增强功能。用户可以借助这款软件将纸质文件转换为可编辑的电子文件&#xff0c;便于传输、签署…

SSH流量分析

原理 总来说&#xff1a;ssh连接大致是以下四个流程 1、tcp三次握手 2、客户端和服务端进行版本详细&#xff0c;加密算法、公钥、的相互交换确认 3、服务端发送新的密钥new keys 交换新的密钥&#xff0c;客户端使用该new key发送空字符串表示没问题 4、进行用户密码登入、以…