当前位置: 首页 > news >正文

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}}

运行结果

相关文章:

qml 实现一个listview

主要通过qml实现listvie功能&#xff0c;主要包括右键菜单&#xff0c;滚动条&#xff0c;拖动改变内容等&#xff0c;c 与 qml之间的变量和函数的调用。 main.cpp #include <QQuickItem> #include <QQmlContext> #include "testlistmodel.h" int main…...

【Leetcode】十六、深度优先搜索 宽度优先搜索 :二叉树的层序遍历

文章目录 1、深度优先搜索算法2、宽度优先搜索算法3、leetcode102&#xff1a;二叉树的层序遍历4、leetcode107&#xff1a;二叉树的层序遍历II5、leetcode938&#xff1a;二叉搜索树的范围和 1、深度优先搜索算法 深度优先搜索&#xff0c;即DFS&#xff0c;从root节点开始&a…...

Ruby教程

Ruby是一种动态的、面向对象的、解释型的脚本语言&#xff0c;以其简洁和易读性而闻名。Ruby的设计哲学强调程序员的生产力和代码的可读性&#xff0c;同时也融合了功能性和面向对象编程的特性。 以下是一个基础的Ruby教程&#xff0c;涵盖了一些基本概念和语法&#xff1a; …...

react + pro-components + ts完成单文件上传和批量上传

上传部分使用的是antd中的Upload组件,具体如下: GradingFilingReportUpload方法是后端已经做好文件流,前端只需要调用接口即可 单文件上传 <Uploadkey{upload_${record.id}}showUploadList{false}accept".xlsx"maxCount{1}customRequest{({ file }) > {const …...

暑假第一周——ZARA仿写

iOS学习 前言首页&#xff1a;无限轮播图商城&#xff1a;分类我的&#xff1a;自定义cell总结 前言 结束了UI的基础学习&#xff0c;现在综合运用开始写第一个demo&#xff0c;在实践中提升。 首页&#xff1a;无限轮播图 先给出效果&#xff1a; 无限轮播图&#xff0c;顾…...

github.com/antchfx/jsonquery基本使用

要在 GitHub 上使用 antchfx/jsonquery 库来查找 JSON 文档中的元素&#xff0c;首先需要了解这个库的基本用法。jsonquery 是一个用于查询 JSON 数据的 Go 语言库&#xff0c;允许使用 XPath 表达式来查找和选择 JSON 数据中的元素。 以下是一些基本步骤和示例&#xff0c;演…...

【python虚拟环境管理】【mac m3】使用poetry管理python项目

文章目录 一. 为什么选择poetry二. poetry相关操作1. 创建并激活环境2. 依赖包管理2.1. 安装项目依赖1.2. 管理不同开发环境的依赖1.3. 依赖维护1.4. 项目相关 Poetry是Python中用于依赖管理和打包的工具。它允许您声明项目所依赖的库&#xff0c;并将为您管理&#xff08;安装…...

《JavaSE》---16.<抽象类接口Object类>

目录 前言 一、抽象类 1.1什么是抽象类 1.2抽象类代码实现 1.3 抽象类特点 1.4抽象类的作用 二、接口 2.1什么是接口 2.2接口的代码书写 2.3 接口使用 2.4 接口特点 2.5 实现多个接口 快捷键&#xff08;ctrl i &#xff09;&#xff1a; 2.6接口的好处 2.7 接…...

简单修改,让UE4/5着色器编译速度变快

简单修改&#xff0c;让UE4/5着色器编译速度变快 目录 简单修改&#xff0c;让UE4/5着色器编译速度变快 一、问题描述 二、解决方法 &#xff08;一&#xff09;硬件升级 &#xff08;二&#xff09;调整相关设置和提升优先级 1.调整相关设置 &#xff08;1&#xff09…...

如何查看极狐GitLab Helm Chart?

GitLab 是一个全球知名的一体化 DevOps 平台&#xff0c;很多人都通过私有化部署 GitLab 来进行源代码托管。极狐GitLab &#xff1a;https://gitlab.cn/install?channelcontent&utm_sourcecsdn 是 GitLab 在中国的发行版&#xff0c;专门为中国程序员服务。可以一键式部署…...

代码随想录算法训练营第十六天| 530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先

写代码的第十六天&#xff0c;自从到了二叉树错误版代码就少了&#xff0c;因为我自己根本没思路&#xff0c;都是看完思路在做&#xff0c;那基本上就是小语法问题&#xff0c;很少有其他问题了&#xff0c;证实了我好菜。。。。。。 还是得写思路啊啊啊啊&#xff0c;写思路好…...

NODEJS复习(ctfshow334-344)

NODEJS复习 web334 下载源码代码审计 发现账号密码 代码逻辑 var findUser function(name, password){ return users.find(function(item){ return name!CTFSHOW && item.username name.toUpperCase() && item.password password; }); }; 名字不等于ctf…...

【Go系列】RPC和grpc

承上启下 介绍完了Go怎么实现RESTFul api&#xff0c;不可避免的&#xff0c;今天必须得整一下rpc这个概念。rpc是什么呢&#xff0c;很多人都想把rpc和http一起对比&#xff0c;但是他们不是一个概念。RPC是一种思想&#xff0c;可以基于tcp&#xff0c;可以基于udp也可以基于…...

【VUE】v-if和v-for的优先级

v-if和v-for v-if 用来显示和隐藏元素 flag为true时&#xff0c;dom元素会被删除达到隐藏效果 <div class"boxIf" v-if"flag"></div>v-for用来进行遍历&#xff0c;可以遍历数字对象数组&#xff0c;会将整个元素遍历指定次数 <!-- 遍…...

【单目3D检测】smoke(1):模型方案详解

纵目发表的这篇单目3D目标检测论文不同于以往用2D预选框建立3D信息&#xff0c;而是采取直接回归3D信息&#xff0c;这种思路简单又高效&#xff0c;并不需要复杂的前后处理&#xff0c;而且是一种one stage方法&#xff0c;对于实际业务部署也很友好。 题目&#xff1a;SMOKE&…...

数据库系统概论:数据库系统的锁机制

引言 锁是计算机协调多个进程或线程并发访问某一资源的机制。在数据库中&#xff0c;数据作为一种共享资源&#xff0c;其并发访问的一致性和有效性是数据库必须解决的问题。锁机制通过对数据库中的数据对象&#xff08;如表、行等&#xff09;进行加锁&#xff0c;以确保在同…...

Django+vue自动化测试平台(28)-- ADB获取设备信息

概述 adb的全称为Android Debug Bridge&#xff0c;就是起到调试桥的作用。通过adb可以在Eclipse中通过DDMS来调试Android程序&#xff0c;说白了就是调试工具。 adb的工作方式比较特殊&#xff0c;采用监听Socket TCP 5554等端口的方式让IDE和Qemu通讯&#xff0c;默认情况下…...

RESTful API设计指南:构建高效、可扩展和易用的API

文章目录 引言一、RESTful API概述1.1 什么是RESTful API1.2 RESTful API的重要性 二、RESTful API的基本原则2.1 资源导向设计2.2 HTTP方法的正确使用 三、URL设计3.1 使用名词而非动词3.2 使用复数形式表示资源集合 四、请求和响应设计4.1 HTTP状态码4.2 响应格式4.2.1 响应实…...

npm下载的依赖包版本号怎么看

npm下载的依赖包版本号怎么看 版本号一般分三个部分&#xff0c;主版本号、次版本号、补丁版本号。 主版本号&#xff1a;一般依赖包发生重大更新时&#xff0c;主版本号才回发生变化&#xff0c;如Vue2.x到Vue3.x。次版本号&#xff1a;当依赖包中发生了一些小变化&#xff…...

css前端面试题

1.什么是css盒子模型&#xff1f; 盒子模型包含了元素内容&#xff08;content&#xff09;、内边距&#xff08;padding&#xff09;、边框&#xff08;border&#xff09;、外边距&#xff08;margin&#xff09;几个要素。 标准盒子模型和IE盒子模型的区别在于其对元素的w…...

国防科技大学计算机基础课程笔记02信息编码

1.机内码和国标码 国标码就是我们非常熟悉的这个GB2312,但是因为都是16进制&#xff0c;因此这个了16进制的数据既可以翻译成为这个机器码&#xff0c;也可以翻译成为这个国标码&#xff0c;所以这个时候很容易会出现这个歧义的情况&#xff1b; 因此&#xff0c;我们的这个国…...

Vue记事本应用实现教程

文章目录 1. 项目介绍2. 开发环境准备3. 设计应用界面4. 创建Vue实例和数据模型5. 实现记事本功能5.1 添加新记事项5.2 删除记事项5.3 清空所有记事 6. 添加样式7. 功能扩展&#xff1a;显示创建时间8. 功能扩展&#xff1a;记事项搜索9. 完整代码10. Vue知识点解析10.1 数据绑…...

树莓派超全系列教程文档--(61)树莓派摄像头高级使用方法

树莓派摄像头高级使用方法 配置通过调谐文件来调整相机行为 使用多个摄像头安装 libcam 和 rpicam-apps依赖关系开发包 文章来源&#xff1a; http://raspberry.dns8844.cn/documentation 原文网址 配置 大多数用例自动工作&#xff0c;无需更改相机配置。但是&#xff0c;一…...

简易版抽奖活动的设计技术方案

1.前言 本技术方案旨在设计一套完整且可靠的抽奖活动逻辑,确保抽奖活动能够公平、公正、公开地进行,同时满足高并发访问、数据安全存储与高效处理等需求,为用户提供流畅的抽奖体验,助力业务顺利开展。本方案将涵盖抽奖活动的整体架构设计、核心流程逻辑、关键功能实现以及…...

从WWDC看苹果产品发展的规律

WWDC 是苹果公司一年一度面向全球开发者的盛会&#xff0c;其主题演讲展现了苹果在产品设计、技术路线、用户体验和生态系统构建上的核心理念与演进脉络。我们借助 ChatGPT Deep Research 工具&#xff0c;对过去十年 WWDC 主题演讲内容进行了系统化分析&#xff0c;形成了这份…...

MongoDB学习和应用(高效的非关系型数据库)

一丶 MongoDB简介 对于社交类软件的功能&#xff0c;我们需要对它的功能特点进行分析&#xff1a; 数据量会随着用户数增大而增大读多写少价值较低非好友看不到其动态信息地理位置的查询… 针对以上特点进行分析各大存储工具&#xff1a; mysql&#xff1a;关系型数据库&am…...

现代密码学 | 椭圆曲线密码学—附py代码

Elliptic Curve Cryptography 椭圆曲线密码学&#xff08;ECC&#xff09;是一种基于有限域上椭圆曲线数学特性的公钥加密技术。其核心原理涉及椭圆曲线的代数性质、离散对数问题以及有限域上的运算。 椭圆曲线密码学是多种数字签名算法的基础&#xff0c;例如椭圆曲线数字签…...

2025盘古石杯决赛【手机取证】

前言 第三届盘古石杯国际电子数据取证大赛决赛 最后一题没有解出来&#xff0c;实在找不到&#xff0c;希望有大佬教一下我。 还有就会议时间&#xff0c;我感觉不是图片时间&#xff0c;因为在电脑看到是其他时间用老会议系统开的会。 手机取证 1、分析鸿蒙手机检材&#x…...

AI书签管理工具开发全记录(十九):嵌入资源处理

1.前言 &#x1f4dd; 在上一篇文章中&#xff0c;我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源&#xff0c;方便后续将资源打包到一个可执行文件中。 2.embed介绍 &#x1f3af; Go 1.16 引入了革命性的 embed 包&#xff0c;彻底改变了静态资源管理的…...

企业如何增强终端安全?

在数字化转型加速的今天&#xff0c;企业的业务运行越来越依赖于终端设备。从员工的笔记本电脑、智能手机&#xff0c;到工厂里的物联网设备、智能传感器&#xff0c;这些终端构成了企业与外部世界连接的 “神经末梢”。然而&#xff0c;随着远程办公的常态化和设备接入的爆炸式…...