Search code examples
qtqmltableview

how to set the input mask only for the selected item in Qt or qml


Requirements

I have a table view which is implemented using 2 tableview column the first column contain a number the 2nd column is a textField.

Now i have to make sure the TextField can only take inputs based on the Digits mentioned in the first column.

For example if the first column reads 3 then in the second column I have to make sure I can enter only 3 characters.

Tried

I was able to create the model appropriately however when I apply the input mask it gets applied to all the cells in the column.

How do I make sure it gets applied only to the selected element:

import QtQuick 2.12
import QtQuick.Window 2.12
import Qt.labs.qmlmodels 1.0
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Table View Example")

    TableView {
        id:peopleTable
        anchors.fill: parent
        clip: true
        model: peopleModel
        property string maskvalue: ""
        onClicked: {
            maskvalue = peopleModel.getpreviouscolumnData(currentIndex)  //this returns the maskvalue from the model side
        }

        TableViewColumn {
            id: firstColumn
            title: "number"
            property var something: delegate.item
            role: "one";
            width: 70;
            delegate: firstColumnComponent
        }

        Component{
            id:firstColumnComponent
            Item {
                id: toplevelItem
                TextEdit{
                    text: styleData.value
                }
            }
        }

        TableViewColumn {title: "settextfield"; role: "two"; width: 70; delegate: secondColumnComponent}

        Component{
            id:secondColumnComponent
            Item {
                id: secondColumnparent
                TextField{
                    text: styleData.value
                    inputMask : maskvalue
                    }
                }
            }
        }

        TableViewColumn {title: "Gender"; role: "three"; width: 70; delegate: TextEdit { text: styleData.value}  }
        TableViewColumn {title: "Age"; role: "four"; width: 70; delegate: TextEdit { text: styleData.value}  }
        TableViewColumn {title: "Phone Number"; role: "five"; width: 100; delegate: TextEdit { text: styleData.value}  }
    }
}

Currently my inputmask gets applied to all the cells in the column, how do I make sure it gets applied only to the selected item?


Solution

  • I got the answer, through the delegate i can access styleData.hasActiveFocus property hence i can do something like

    inputMask : styleData.selected ?  "999": ""
    

    This worked, with this i can set mask for every individual element in a column