当前位置: 首页 > 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}}

运行结果

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 系统架构设计师教程(清华第二版) 第3章 信息系统基础知识-3.3 管理信息系统(MIS)-解读
  • C++派生类对基类成员的访问
  • [Linux安全运维] OpenVPN部署
  • 吴恩达大模型LLM系列课程学习(更新42门课程)
  • 初步认识HTML
  • 【视频讲解】神经网络、Lasso回归、线性回归、随机森林、ARIMA股票价格时间序列预测|附代码数据
  • python3.11SSL: SSLV3_ALERT_HANDSHAKE_FAILURE
  • 搭建个人智能家居 7 - 空气颗粒物检测
  • 【.NET全栈】ASP.NET开发Web应用——站点导航技术
  • 操作系统发展简史(Unix/Linux 篇 + DOS/Windows 篇)+ Mac 与 Microsoft 之风云争霸
  • 【BUG】已解决:raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)
  • 学习SQL权限管理的基础知识
  • 查询优化 -- UNION 用法
  • 路由数据获取及封装方法
  • 数据结构(Java):力扣牛客 二叉树面试OJ题(一)
  • 《Javascript数据结构和算法》笔记-「字典和散列表」
  • 【Linux系统编程】快速查找errno错误码信息
  • docker python 配置
  • Fastjson的基本使用方法大全
  • golang中接口赋值与方法集
  • go语言学习初探(一)
  • Linux中的硬链接与软链接
  • node-glob通配符
  • oschina
  • React-Native - 收藏集 - 掘金
  • Spring-boot 启动时碰到的错误
  • vue2.0一起在懵逼的海洋里越陷越深(四)
  • 复杂数据处理
  • 将回调地狱按在地上摩擦的Promise
  • 那些年我们用过的显示性能指标
  • 学习笔记TF060:图像语音结合,看图说话
  • 数据可视化之下发图实践
  • # 日期待t_最值得等的SUV奥迪Q9:空间比MPV还大,或搭4.0T,香
  • #LLM入门|Prompt#1.7_文本拓展_Expanding
  • (1)Jupyter Notebook 下载及安装
  • (2022 CVPR) Unbiased Teacher v2
  • (STM32笔记)九、RCC时钟树与时钟 第二部分
  • (纯JS)图片裁剪
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (剑指Offer)面试题41:和为s的连续正数序列
  • (六)vue-router+UI组件库
  • (算法)区间调度问题
  • (一)Java算法:二分查找
  • (转)Linux整合apache和tomcat构建Web服务器
  • (转)真正的中国天气api接口xml,json(求加精) ...
  • (转贴)用VML开发工作流设计器 UCML.NET工作流管理系统
  • ./configure,make,make install的作用
  • .md即markdown文件的基本常用编写语法
  • .NET Standard / dotnet-core / net472 —— .NET 究竟应该如何大小写?
  • .Net多线程Threading相关详解
  • .net开发日常笔记(持续更新)
  • .net通用权限框架B/S (三)--MODEL层(2)
  • [] 与 [[]], -gt 与 > 的比较
  • [Armbian] 部署Docker版Home Assistent,安装HACS并连接米家设备
  • [AUTOSAR][诊断管理][ECU][$37] 请求退出传输。终止数据传输的(上传/下载)