QML TableView 表格总结

概要

qml 的资料相对qt widget来说,还是偏少啊,无论从帮助文档还是从网上搜索。笔者项目中遇到的一些展示控件,需要用tableview来展示,总结了一下两种方式,都是基于Tableview来实现的,一种是基于 QtQuick.Controls 1.4 版本,一种是高版本 QtQuick 2.14

基于QtQuick.Controls 1.4 版本的TableView用法

几种最重要的几个属性就是

headerDelegate : Component
itemDelegate : Component
model : model
rowDelegate : Component
selection : Selection

用法举例

下述代码中实现了表格的删除、复制、上移、下移、多选、多选的复制、多选的删除,全部勾选,右键菜单等等功能

效果如图:
在这里插入图片描述

TableView{
    id:_tableView

    anchor.fill:parent
    headerDelegate: headerDele  // headerDelegate
    rowDelegate :rowDele	//rowDelegate 
    selectionMode:SelectionMode.ExtendedSelection
    horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff//隐藏水平滚动条
    frameVisible: false
    property bool interactive : true
    property var curTestRow : 0
    property  var testSelectIndexList : []
    property real firstColumnWidth : 80
    property real singleLineHeight:32
    property var headerModel: [qsTr("序号"),qsTr("测试名称"),qsTr("测试条件"),qsTr("最小值"),qsTr("测试值"),qsTr("最大值"),qsTr("结果"),qsTr("合格数"),qsTr("失效数"),qsTr("良率"),qsTr("分析")];
    property var roleModel: ["testCheckState","testName","condition","min","testResult","max","state","passNumber","failedNumber","passRate","analysis"];
    function getColumnWidth(col)
    {
        switch(col)
        {
        case 0:
            return firstColumnWidth;
        case 1:
            return Math.floor((_tableView.width-firstColumnWidth-11)*0.1);
        case 2:
            return Math.floor((_tableView.width-firstColumnWidth-11)*0.25);
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
            return Math.floor((_tableView.width-firstColumnWidth-11)*0.08125);
        default:
            return Math.floor((_tableView.width-firstColumnWidth-11)*0.08125);
        }
    }

    //遍历
    function getAlllData() {
        console.log("get all data",_tableView.model.count)
        for (var i = 0; i < _tableView.model.count; ++i) {
            var obj = _tableView.model.get(i);
            var str = JSON.stringify(obj).toLowerCase();
            console.log("str=", str);
        }
    }

    function getLibTypeIndex() //获取lib这种测试类型的行索引
    {
        for (var i = 0; i < _tableView.model.count; ++i) {
            var obj = _tableView.model.get(i);
            if(obj.testType === "lib")
            {
                return i;
            }
        }

        return 0;
    }

    function addOneTopRow(obj)
    {
        var libIndex = getLibTypeIndex();
        console.log("addOneTopRow libindex=", libIndex)
        if(libIndex > 0)
            _tableModel.insert(libIndex,obj);
        else
            _tableModel.insert(0,obj);
    }

    function addOneRow()
    {
        var uuid = TestManager.addTmpLib();
        var count = _tableModel.count;
        var rowObj = TestManager.getOneLibByUuid(uuid)
        var iunit = rowObj["resultUnit"];
        var displayTexMax = UILogic.disPlay(Number(rowObj["max"]),iunit)
        var displayTexMin = UILogic.disPlay(Number(rowObj["min"]),iunit)
        rowObj["max"] = displayTexMax;
        rowObj["min"] = displayTexMin;
        console.log("testTable add row",JSON.stringify(rowObj) )
        _tableModel.append(rowObj);
    }

    function updateOneRow(libname,uuid)
    {
        TestManager.applyTmpLib(libname,uuid);
        //更新当前编辑过的行,因为需要display转换
        var rowObj = TestManager.getOneLib(libname);
        var imax = rowObj["max"];
        var imin = rowObj["min"]
        var iunit = rowObj["resultUnit"];
        var displayTexMax = UILogic.disPlay(Number(rowObj["max"]),iunit)
        var displayTexMin = UILogic.disPlay(Number(rowObj["min"]),iunit)
        rowObj["max"] = displayTexMax;
        rowObj["min"] = displayTexMin;
        _tableModel.setProperty(_tableView.currentRow,"testName",libname)
        _tableModel.setProperty(_tableView.currentRow,"condition",rowObj["condition"])
        _tableModel.setProperty(_tableView.currentRow,"min",rowObj["min"])
        _tableModel.setProperty(_tableView.currentRow,"max",rowObj["max"])
        _tableModel.setProperty(_tableView.currentRow,"testResult","")
        _tableModel.setProperty(_tableView.currentRow,"resultUnit",iunit)
    }

    function updateTestResult(uuid,value,testStatus,passNum,failedNum,passRate)  //0 失败 1 成功
    {
        for(var i=0;i<_tableModel.count;i++)
        {
            var obj = _tableModel.get(i);
            if(obj["uuid"] === uuid)
            {
                console.log("updateTestResult",value,testStatus)
                var iunit = obj["resultUnit"];
                var displayTexValue = UILogic.disPlay(value,iunit)
                console.log(typeof displayTexValue,displayTexValue);
                _tableModel.setProperty(i,"state",testStatus)
                _tableModel.setProperty(i,"testResult",displayTexValue)
                _tableModel.setProperty(i,"passNumber",String(passNum))
                _tableModel.setProperty(i,"failedNumber",String(failedNum))
                _tableModel.setProperty(i,"passRate",passRate)
                //_tableModel.setProperty(i,"static",staticInfo)
            }
        }
    }

    function updatePatMinMax(uuid,min,max)
    {
        for(var i=0;i<_tableModel.count;i++)
        {
            var rowObj = _tableModel.get(i);
            if(rowObj["uuid"] === uuid)
            {
                var imax = rowObj["max"];
                var imin = rowObj["min"];
                console.log("updatePatMinMax before",imin,imax)
                var iunit = rowObj["resultUnit"];
                var displayTexMin = UILogic.disPlay(min,iunit)
                var displayTexMax = UILogic.disPlay(max,iunit)
                rowObj["max"] = displayTexMax;
                rowObj["min"] = displayTexMin;

                console.log("updatePatMinMax",min,max)
                _tableModel.setProperty(i,"min",displayTexMin)
                _tableModel.setProperty(i,"max",displayTexMax)
            }
        }
    }

    function updateOneKerlwenTest(desobj)
    {
        for(var i=0;i<_tableModel.count;i++)
        {
            var obj = _tableModel.get(i);
            if(obj["uuid"] === desobj.uuid)
            {
                _tableModel.setProperty(i,"min",desobj.min)
                _tableModel.setProperty(i,"max",desobj.max)
            }
        }
    }

    function updateOneKerlwenTestResult(name,result,bpass)
    {
        for(var i=0;i<_tableModel.count;i++)
        {
            var obj = _tableModel.get(i);
            if(obj["testName"] === name)
            {
                _tableModel.setProperty(i,"testResult",String(UILogic.getFixedNumber(result,5)))
                _tableModel.setProperty(i,"state",bpass?1:0)
                break;
            }
        }
    }

    function haveKerlwenOrThresholdEnabledList()
    {
        for(var i=0;i<_tableModel.count;i++)
        {
            var obj = _tableModel.get(i);
            if(obj["testCheckState"] === 2 && obj["testType"]!=="lib")
            {
                return true;
            }
        }

        return false;
    }

    function getEnabledList()
    {
        var enableList = [];
        testSelectIndexList = [];
        for(var i=0;i<_tableModel.count;i++)
        {
            var obj = _tableModel.get(i);
            //console.log("getEnabledList",i,JSON.stringify(obj))
            if(obj["testCheckState"] === 2 && obj["testType"]==="lib")
            {
                enableList.push(obj["uuid"]);
                testSelectIndexList.push(i);
            }
        }
        return enableList;
    }

    function clearAllResult()
    {
        for(var i=0;i<_tableModel.count;i++)
        {
            _tableModel.setProperty(i,"testResult","")
            _tableModel.setProperty(i,"state",3)
            //_tableModel.setProperty(i,"static","")
            _tableModel.setProperty(i,"passNumber","")
            _tableModel.setProperty(i,"failedNumber","")
            _tableModel.setProperty(i,"passRate","")
        }
    }

    function enableTable(enable)
    {
        _tableView.interactive = enable;
        if(enable === false)
            _tableView.selection.clear();
    }

    function removeRow()
    {
        var i = 0;
        _tableView.selection.forEach( function(rowIndex) {
            console.log("removeRow",rowIndex)
            var newValue = rowIndex - i;
            var curObj = _tableModel.get(newValue);
            console.log("removeRow",JSON.stringify(curObj),curObj["testName"])
            if(curObj.testType === "lib")
                TestManager.removeOneLibByUuid(curObj["uuid"]);
            else if(curObj.testType === "kerlwen")
            {
                TestManager.removeOneKerlwenTest(curObj["testName"])
            }
            else if(curObj.testType === "threshold")
            {
                TestManager.removeOneThresholdTest(curObj["testName"])
            }
            _tableModel.remove(newValue)
            i++;
        } )
        _tableView.selection.clear();
    }

    function upRow()
    {
        //判断是否已经选中第一行
        var isTop = false;

        var indexList = [];

        _tableView.selection.forEach( function(rowIndex) {
            indexList.push(rowIndex);
            if(rowIndex === 0)
                isTop = true;
        })

        if(isTop)
            return;

        var top;
        var bottom;
        var count= _tableView.selection.count;
        var i=0;
        _tableView.selection.forEach( function(rowIndex) {
            if(i === 0)
                top = rowIndex;
            if(i=== (count-1))
                bottom = rowIndex;
            _tableModel.move(rowIndex,rowIndex-1,1);
            TestManager.moveUpOneLib(rowIndex);
            i++;
        } )

        _tableView.selection.clear();
        for(var n2 = 0; n2<indexList.length; n2++)
            _tableView.selection.select(Number(indexList[n2])-1);
        //_tableView.selection.select(top-1,bottom-1);
    }

    function downRow()
    {
        //判断是否已经到了最下面
        var isLast = false;
        _tableView.selection.forEach( function(rowIndex) {
            if(rowIndex === (_tableModel.count-1))
                isLast = true;
        })

        if(isLast)
            return;

        //反向获得新的list 需要先移动最下面的行
        var list = [];
        var revertList;
        _tableView.selection.forEach( function(rowIndex) {
            list.push(rowIndex);
        } )

        revertList = Utils.revert(list);
        if(revertList.length > 0)
        {
            var top;
            var bottom;
            var count= _tableView.selection.count;
            for(var n = 0; n<revertList.length; n++)
            {
                var rowIndex = Number(revertList[n]);
                if(n === 0)
                    bottom = rowIndex;
                if(n=== (revertList.length-1))
                    top = rowIndex;
                _tableModel.move(rowIndex,rowIndex+1,1);
                TestManager.moveDownOneLib(rowIndex);
            }

            _tableView.selection.clear();

            for(var n2 = 0; n2<revertList.length; n2++)
                _tableView.selection.select(Number(revertList[n2])+1);
        }
    }

    function copyRow()
    {
        //复制的时候不能直接操控 curobj
        //ex var newObj = curObj
        // newObj["testName"] = ....
        _tableView.selection.forEach( function(rowIndex) {
            var curObj = _tableModel.get(rowIndex);
            if(curObj.testType !== "lib")
                return;
            var newObj = UILogic.deepCopyViaJson(curObj);
            newObj["uuid"] = Utils.genUuid();
            newObj["testName"] = TestManager.getCopyName(curObj["testName"]);
            newObj["testResult"] = ""
            newObj["state"] = 3
            newObj["passNumber"] = ""
            newObj["failedNumber"] = ""
            newObj["passRate"] = ""
            //newObj["static"] = ""
            console.log("copy row des",JSON.stringify(newObj))

            TestManager.copyOneLib(curObj["uuid"], newObj["testName"],newObj["uuid"]);
            _tableModel.insert(_tableModel.count,newObj)
            AppSettings.testModifyed = true
        } )
    }

    function selectAll()
    {
        _tableView.selection.selectAll();
    }

    function deSelectAll()
    {
        _tableView.selection.clear();
    }

    function selectNext(index)
    {
        console.log("selectNext",index,testSelectIndexList[index])
        curTestRow = testSelectIndexList[index];
        _tableView.selection.select(testSelectIndexList[index])
        _tableModel.setProperty(testSelectIndexList[index],"state",2)
    }

    function updateCurSelect()
    {
        console.log("updateCurSelect curTestRow=",curTestRow)
        if(_tableModel.count === 0)
            return;
        var obj = _tableModel.get(curTestRow);
        if(obj["state"] === 2)
        {
            _tableModel.setProperty(curTestRow,"state",3)
        }
    }

    function enableAll()
    {
        console.log("enableAll")
        for(var i=0;i<_tableModel.count;i++)
        {
            _tableModel.setProperty(i,"testCheckState",2)
        }
    }

    function enableNull()
    {
        console.log("enableNull")
        for(var i=0;i<_tableModel.count;i++)
        {
            _tableModel.setProperty(i,"testCheckState",0)
        }
    }

    function getCurLibName()
    {
        var curObj = _tableModel.get(_tableView.currentRow);
        return curObj.testName;
    }

    function getCurTestInfo()
    {
        var curObj = _tableModel.get(_tableView.currentRow);
        console.log("getCurTestInfo",JSON.stringify(curObj))
        var uuid = curObj.uuid;
        var testType = curObj.testType
        return {uuid,testType};
    }

    function initLibData()
    {
        var libarray = TestManager.getLibs();
        for(var i=0;i<libarray.length;i++)
        {
            var obj = libarray[i];
            var imax = obj["max"];
            var imin = obj["min"]
            var iunit = obj["resultUnit"];
            var displayTexMax = UILogic.disPlay(obj["max"],iunit)
            var displayTexMin = UILogic.disPlay(obj["min"],iunit)
            obj["max"] = displayTexMax;
            obj["min"] = displayTexMin;
            console.log("initLibData",JSON.stringify(obj))
            _tableModel.append(libarray[i]);
        }
    }

    function initKerlwenData()
    {
        var arrays = TestManager.getKerlwenTestArray();
        for(var i=0;i<arrays.length;i++)
        {
            _tableModel.append(arrays[i]);
        }
    }

    function initThresholdData()
    {
        var arrays = TestManager.getThresholdTestArray();
        for(var i=0;i<arrays.length;i++)
        {
            _tableModel.append(arrays[i]);
        }
    }

    function initData()
    {
        if(TestManager.haveCategory() === false)
            return;
        AppSettings.curGroup = TestManager.getCurCategoryName();
        _tableModel.clear();
        initKerlwenData();
        initThresholdData();
        initLibData();
    }

    model: ListModel{
        id:_tableModel
    }

    Menu { // 右键菜单
            title: "Edit"
            id: contentMenu
            MenuItem {
                text: qsTr("增加")
                shortcut: "Ctrl+A"
                onTriggered: {
                    addClicked()
                }
            }

            MenuItem {
                text: qsTr("删除")
                shortcut: "Ctrl+D"
                onTriggered: {
                    removeRow()
                }
            }

            MenuItem {
                text: qsTr("复制")
                shortcut: "Ctrl+C"
                onTriggered: {
                    copyRow();
                }
            }

            MenuSeparator { }

            MenuItem {
                text: qsTr("上移")
                onTriggered: {
                    upRow();
                }
            }

            MenuItem {
                text: qsTr("下移")
                onTriggered: {
                    downRow();
                }
            }

            MenuItem {
                text: qsTr("全部勾选")
                onTriggered: {
                    enableAll();
                }
            }

            MenuItem {
                text: qsTr("全部取消勾选")
                onTriggered: {
                    enableNull();
                }
            }

            MenuItem {
                text: qsTr("清除结果")
                onTriggered: {
                    clearAllResult();
                    TestManager.clearAllResult();
                }
            }
//            Menu {
//                title: "More Stuff"
//                MenuItem {
//                    text: "Do Nothing"
//                }
//            }
        }


    //定义表头的组件
    Component{
        id:headerDele
        Rectangle{
            implicitWidth:  _tableView.width*0.1
            implicitHeight:  singleLineHeight+10
            border.width: 1
            border.color: "#838B8B"
            color: "#4F4F4F"
            AppText {
                anchors.centerIn: parent
                text: styleData.value
                color:"white"
            }
        }
    }

    //定义行的组件
    Component{
        id:rowDele
        Rectangle{
            width: _tableView.width
            height: singleLineHeight
            //color: styleData.selected?"#450000ff":"#22000000"
            color: styleData.selected ? Style.color_cyan_secondary : Style.color_elevation_bg_low
            //color: (/*styleData.selected || */styleData.row === _tableView.currentRow )? Style.color_cyan_secondary : Style.color_elevation_bg_low

            MouseArea
            {
                anchors.fill: parent
                acceptedButtons: Qt.RightButton
                onClicked: {
                    console.log("right button clikced",_tableView.selection.count)
                    if(_tableView.selection.count === 0)
                    {
                        _tableView.selection.clear()
                        _tableView.selection.select(styleData.row)
                        _tableView.currentRow = styleData.row
                    }
                    contentMenu.popup()
                }
            }
        }
    }
    //序号
    TableViewColumn{
        role:roleModel[0]
        title: headerModel[0]
        width: getColumnWidth(0)
        delegate: Rectangle{
            color: "transparent"
            height:  singleLineHeight
            border.width: 1
            border.color: Style.controlBorderColor
            enabled: interactive===true

            AppCheckBox
            {
                checkState: Number(styleData.value)===2?Qt.Checked:Qt.Unchecked
                text: styleData.row+1
                textfont.pixelSize : Style.font_size_cn_20
                enabled: UserManager.curUserPermission===Permission.Permission_admin || UserManager.curUserPermission===Permission.Permission_engineer
                onCheckStateChanged:
                {
                    //console.log("checkState",styleData.row, checkState)
                    if(styleData.row === -1)
                        return;

                    _tableModel.setProperty(styleData.row,"testCheckState",checkState)
                    var obj = _tableModel.get(styleData.row);
                    if(obj.testType === "lib")
                    {
                        TestManager.setEnaleLib(obj["uuid"],checkState==Qt.Checked)
                    }
                    else if(obj.testType === "kerlwen")
                    {
                        TestManager.setEnableKerlwenTest(obj["uuid"],checkState==Qt.Checked)
                    }
                    else if(obj.testType === "threshold")
                    {
                        TestManager.setEnableThresholdTest(obj["uuid"],checkState==Qt.Checked)
                    }
                }

            }
        }
    }

    //实验名称
    TableViewColumn{
        role:roleModel[1]
        title: headerModel[1]
        width: getColumnWidth(1)
        delegate: Rectangle{
            color: "transparent"
            height:  singleLineHeight
            border.width: 1
            border.color: Style.controlBorderColor
            AppText{
                anchors.centerIn: parent
                text:styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
                width: parent.width
                elide: Text.ElideRight
            }

        }
    }

    //试验条件
    TableViewColumn{
        role:roleModel[2]
        title: headerModel[2]
        width: getColumnWidth(2)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor
            AppText{
                anchors.centerIn: parent
                text:styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
            }
        }
    }

    //最小值
    TableViewColumn{
        role:roleModel[3]
        title: headerModel[3]
        width: getColumnWidth(3)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor
            AppText{
                anchors.centerIn: parent
                //width: parent.width
                text:styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
                elide: Text.ElideRight
            }
        }

    }
    //结果值
    TableViewColumn{
        role:roleModel[4]
        title: headerModel[4]
        width: getColumnWidth(4)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor
            AppText{
                anchors.centerIn: parent
                text:styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
            }

        }
    }
    //最大值
    TableViewColumn{
        role:roleModel[5]
        title: headerModel[5]
        width: getColumnWidth(5)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor

            AppText{
                anchors.centerIn: parent
                text: styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
            }
        }
    }

    //是否合格
    TableViewColumn{
        role:roleModel[6]
        title: headerModel[6]
        width: getColumnWidth(6)
        delegate: Rectangle{
            id:resultDelegate
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor

            //0 失败 1成功 2正在测试 3 未开始
            AppIcon{
                //anchors.centerIn: parent
                id:_resultPic
                anchors.verticalCenter: parent.verticalCenter
                width: 26
                height: 26
                x:(parent.width-width)/2
                visible: styleData.value !== 2

                source: {
                    if(styleData.value === 3)
                    {
                        return "";
                    }
                    else if(styleData.value === 0)
                    {
                        return "qrc:/images/unpass.png";
                    }
                    else if(styleData.value === 1)
                    {
                        return "qrc:/images/pass.png";
                    }

                    return "";
                }
            }


            AppIcon{
                id:_resultTestPic
                anchors.verticalCenter: parent.verticalCenter
                width: 26
                height: 26
                x:(parent.width-width)/2
                visible: styleData.value === 2
                NumberAnimation on x {
                    running: styleData.value === 2
                    loops: Animation.Infinite
                    from: 0; to: parent.width-_resultTestPic.width; duration: 200
                }

                source: "qrc:/images/testing.png";
            }
        }
    }

    TableViewColumn{
        role:roleModel[7]
        title: headerModel[7]
        width: getColumnWidth(7)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor

            AppText{
                anchors.centerIn: parent
                text: styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
            }
        }
    }

    TableViewColumn{
        role:roleModel[8]
        title: headerModel[8]
        width: getColumnWidth(8)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor

            AppText{
                anchors.centerIn: parent
                text: styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
            }
        }
    }

    TableViewColumn{
        role:roleModel[9]
        title: headerModel[9]
        width: getColumnWidth(9)
        delegate: Rectangle{
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor

            AppText{
                anchors.centerIn: parent
                text: styleData.value
                font.styleName: "Regular"
                font.pixelSize : Style.font_size_cn_22
            }
        }
    }

    TableViewColumn{
        role:roleModel[10]
        title: headerModel[10]
        width: getColumnWidth(10)
        delegate: Rectangle{
            id:waveDelegate
            height:  singleLineHeight
            color: "transparent"
            border.width: 1
            border.color: Style.controlBorderColor
            enabled: interactive===true
            AppUnderlineButton
            {
                anchors.centerIn: parent
                font.pixelSize: Style.font_size_cn_20
                text: qsTr("数据分析")
                textColor: "#FF7F50"
                onSigClicked:
                {
                    _tableView.currentRow = styleData.row
                    _tableView.selection.clear();
                    _tableView.selection.select(styleData.row)
                    var obj = getCurTestInfo();
                    AppSettings.testType = obj.testType
                    if(obj.testType === "lib")
                    {
                        TestManager.setTempEditLib(obj.uuid);
                        globalUI.showLibAnalysisPage(styleData.row);
                    }
                }
            }
        }
    }

}

删除功能实现

function removeRow()
{
        var i = 0;
        _tableView.selection.forEach( function(rowIndex) {
            console.log("removeRow",rowIndex)
            var newValue = rowIndex - i;
            _tableModel.remove(newValue)
            i++;
        } )
        _tableView.selection.clear();*
}

复制功能实现

对业务代码进行了删除,只保留了跟表格有关的代码

function copyRow()
{
        _tableView.selection.forEach( function(rowIndex) {
            var curObj = _tableModel.get(rowIndex);
            _tableModel.insert(_tableModel.count,curObj )
        } )
}

上移功能实现

function upRow()
    {
        //判断是否已经选中第一行
        var isTop = false;

        var indexList = [];

        _tableView.selection.forEach( function(rowIndex) {
            indexList.push(rowIndex);
            if(rowIndex === 0)
                isTop = true;
        })

        if(isTop)
            return;

        var top;
        var bottom;
        var count= _tableView.selection.count;
        var i=0;
        _tableView.selection.forEach( function(rowIndex) {
            if(i === 0)
                top = rowIndex;
            if(i=== (count-1))
                bottom = rowIndex;
            _tableModel.move(rowIndex,rowIndex-1,1);
            TestManager.moveUpOneLib(rowIndex);
            i++;
        } )

        _tableView.selection.clear();
        for(var n2 = 0; n2<indexList.length; n2++)
            _tableView.selection.select(Number(indexList[n2])-1);
    }

下移功能实现

function downRow()
    {
        //判断是否已经到了最下面
        var isLast = false;
        _tableView.selection.forEach( function(rowIndex) {
            if(rowIndex === (_tableModel.count-1))
                isLast = true;
        })

        if(isLast)
            return;

        //反向获得新的list 需要先移动最下面的行
        var list = [];
        var revertList;
        _tableView.selection.forEach( function(rowIndex) {
            list.push(rowIndex);
        } )
        revertList = Utils.revert(list);
        if(revertList.length > 0)
        {
            var top;
            var bottom;
            var count= _tableView.selection.count;
            for(var n = 0; n<revertList.length; n++)
            {
                var rowIndex = Number(revertList[n]);
                if(n === 0)
                    bottom = rowIndex;
                if(n=== (revertList.length-1))
                    top = rowIndex;
                _tableModel.move(rowIndex,rowIndex+1,1);
            }

            _tableView.selection.clear();
            for(var n2 = 0; n2<revertList.length; n2++)
                _tableView.selection.select(Number(revertList[n2])+1);
        }
    }

全选和全不选

	function selectAll()
    {
        _tableView.selection.selectAll();
    }

    function deSelectAll()
    {
        _tableView.selection.clear();
    }

右键菜单

右键菜单主要是在 rowDelegate 做了操作

	Component{
        id:rowDele
        Rectangle{
            width: _tableView.width
            height: singleLineHeight
            //color: styleData.selected?"#450000ff":"#22000000"
            color: styleData.selected ? Style.color_cyan_secondary : Style.color_elevation_bg_low
            //color: (/*styleData.selected || */styleData.row === _tableView.currentRow )? Style.color_cyan_secondary : Style.color_elevation_bg_low

            MouseArea
            {
                anchors.fill: parent
                acceptedButtons: Qt.RightButton
                onClicked: {
                    console.log("right button clikced",_tableView.selection.count)
                    if(_tableView.selection.count === 0)
                    {
                        _tableView.selection.clear()
                        _tableView.selection.select(styleData.row)
                        _tableView.currentRow = styleData.row
                    }
                    contentMenu.popup()
                }
            }
        }
    }

其他的可直接参考源码

基于QtQuick 2.14 版本的TableView用法

主要关注一下属性设置

columnWidthProvider : var
rowHeightProvider : var

代码举例

Item {
    id:root

    //TableModelColumn{ display: "radio+"; edit: "radio-" } // using two roles
    //TableModelColumn{ display: "drift+"; edit: "drift-" } // using two roles
    property var type // "out" "in"
    property int rowHeight : 40
    property int hearderHeight:45
    property var headerModel: [qsTr("档位"),qsTr("+      系数      -"),qsTr("+      零漂(V/uA)      -")];
    property var para1: ""
    property var para2: ""
    property var para3: ""
    property var para4: ""
    property var columnWidths: [260, 480, 480]
    property var tableWidth : {
        getTableWidth()+5
    }
    function getColumnWidth(column)
    {
        return columnWidths[column]
    }

    function getTableWidth()
    {
        var w=0;
        for(var i=0;i<columnWidths.length;i++)
        {
            w += columnWidths[i];
            console.log("columnWidths[i]",columnWidths[i])
        }
        console.log("getTableWidth",w)
        return w;
    }

    width: tableWidth
    height: Math.max( tablemodel.rowCount*rowHeight+hearderHeight+30,300)
    visible: true

    TableView {
        id: _tableView
        width: parent.width
        height:parent.height*0.95
        //anchors.horizontalCenter: parent.horizontalCenter
        clip: true // clip content to table dimensions
        boundsBehavior: Flickable.StopAtBounds
        reuseItems: false // forces table to destroy delegates
        columnSpacing: 1 // in case of big/row spacing, you need to take care of width/height providers (to get along with it)

        // margins to vertical/horizontal headers
        //leftMargin: verticalHeader.width
        topMargin: horizontalHeader.height

        // scrollbar config
        ScrollBar.horizontal: ScrollBar{
            //policy: "AlwaysOn"
        }
        ScrollBar.vertical: ScrollBar{
            //policy: "AlwaysOn"
        }
        ScrollIndicator.horizontal: ScrollIndicator { }
        ScrollIndicator.vertical: ScrollIndicator { }

        // width and height providers
        columnWidthProvider: function(column){ return columnWidths[column] }
        rowHeightProvider: function (column) { return rowHeight }

        // table horizontal header
        Row {
            id: horizontalHeader
            y: _tableView.contentY
            z: 2
            Repeater {
                model: _tableView.columns
                Rectangle {
                    width: _tableView.columnWidthProvider(modelData)
                    height: headerTextInput.paintedHeight+8
                    color:  "#2d2d2d"
                    border.width: 1
                    border.color: "#838383"
                    Text {
                        id: headerTextInput
                        anchors.centerIn: parent
                        text: headerModel[index]
                        font.pixelSize: Style.font_size_cn_24
                        color: "#e5e5e5"
                    }
                }
            }
        }
        // defining model columns' roles
        model: TableModel {
            id: tablemodel
            TableModelColumn{ display: "gearName" }
            TableModelColumn{ display: para1; edit: para2 } // using two roles
            TableModelColumn{ display: para3; edit: para4 } // using two roles
        }

        // defining custom delegates and model connection
        delegate: DelegateChooser {
            DelegateChoice {
                column: 0
                delegate:Rectangle {
                    border.width: 1
                    border.color: "#7f838c"
                    Text {
                        anchors.centerIn: parent
                        verticalAlignment: Text.AlignVCenter;
                        horizontalAlignment: Text.AlignHCenter
                        text: display
                        font.pixelSize: Style.font_size_cn_22
                        color: "#000000"
                    }
                }
            }

            DelegateChoice {
                column: 1
                delegate: RowLayout { // two textfields in same column model
                    spacing: 0
                    APPLineField {
                        implicitWidth: parent.width / 2
                        text: model.display
                        placeholderText: "+"
                        selectByMouse: true
                        font.italic: true
                        onMyEditFinished:model.display = Number(this.text)
                        //onEditingFinished: model.display = Number(this.text)
                        font.pixelSize: Style.font_size_cn_24
                        type:AppSettings.appkeyboard_number
                        childType: AppSettings.numberKeyBoard_OnlyDigit
                    }
                    APPLineField {
                        implicitWidth: parent.width / 2
                        text: model.edit
                        placeholderText: "-"
                        selectByMouse: true
                        font.italic: true
                        font.pixelSize: Style.font_size_cn_24
                        type:AppSettings.appkeyboard_number
                        childType: AppSettings.numberKeyBoard_OnlyDigit
                        //onEditingFinished:
                        onMyEditFinished:
                        {
                            model.edit = Number(this.text)
                            //printAlllData();
                        }
                    }
                }
            }

            DelegateChoice {
                column: 2
                delegate: RowLayout { // two textfields in same column model
                    spacing: 0
                    APPLineField {
                        implicitWidth: parent.width / 2
                        text: model.display
                        placeholderText: "+"
                        selectByMouse: true
                        font.pixelSize: Style.font_size_cn_24
                        font.italic: true
                        type:AppSettings.appkeyboard_number
                        childType: AppSettings.numberKeyBoard_OnlyDigit
                        /*onEditingFinished */onMyEditFinished: model.display = Number(this.text)
                    }
                    APPLineField {
                        implicitWidth: parent.width / 2
                        text: model.edit
                        placeholderText: "-"
                        selectByMouse: true
                        font.italic: true
                        font.pixelSize: Style.font_size_cn_24
                        type:AppSettings.appkeyboard_number
                        childType: AppSettings.numberKeyBoard_OnlyDigit
                        /*onEditingFinished*/ onMyEditFinished: model.edit = Number(this.text)
                    }
                }
            }

        }
    }

    Timer
    {
        id:_testTimer
        interval: 1000
        repeat: false
        onTriggered:
        {

            console.log("Calitable view append row")
            tablemodel.appendRow({ "gearName":"2-5v",
                                       "radio+":"小花",
                                       "radio-":"女",
                                       "drift+":"汉",
                                       "drift-":"27",});
            _tableView.forceLayout() // forces _tableView update
            initTableData();
        }
    }

    function reset()
    {
        for (var i = 0; i < tablemodel.rowCount; ++i) {
            var obj = tablemodel.getRow(i);
            console.log("rest",JSON.stringify(obj),para1,para2,para3,para4,obj.hasOwnProperty(para1))
            if(obj.hasOwnProperty(para1))
            {
                obj[para1] = 0;
            }

            if(obj.hasOwnProperty(para2))
            {
                obj[para2] = 0;
            }

            if(obj.hasOwnProperty(para3))
            {
                obj[para3] = 0;
            }

            if(obj.hasOwnProperty(para4))
            {
                obj[para4] = 0;
            }

            tablemodel.setRow(i,obj)
        }
    }

    function getAllData()
    {
        var dataArray = new Array;
        for (var i = 0; i < tablemodel.rowCount; ++i) {
            console.log("str=", JSON.stringify(tablemodel.getRow(i)));
            dataArray.push(tablemodel.getRow(i))
        }

        return dataArray;
    }

    function printAlllData() {
        console.log("Calitable view get all data",tablemodel.rowCount,_tableView.height)
        for (var i = 0; i < tablemodel.rowCount; ++i) {
            var obj = tablemodel.getRow(i);
            var str = JSON.stringify(obj)//.toLowerCase();
           console.log("str=", str);
        }
    }

    function updateaTableData(address)
    {
     
    }
}

实现的效果如图 :
在这里插入图片描述

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值