Search code examples
qtqmlqtquick2qtquickcontrols

How to make a signal like onEditingFinished available to individual TextInput elements reusing one common TextInput defined


I am new to QML & Qt. I am trying to make multiple TextInput elements which can send their own text when onEditingFinished is triggered. Following is a TextInput item that I have created in MyTextField.qml:

MyTextField.qml

import QtQuick 2.5
import QtQuick.Controls 1.4

Item {

implicitHeight: 200
implicitWidth: 1000

property alias inputMethodHints: myTextField.inputMethodHints
property alias text: myTextField.text

Rectangle {
    anchors.fill: parent
    radius: 40
  }


TextInput {
    id: myTextField
    objectName: "myTextField"
    anchors.fill: parent
    verticalAlignment: Text.AlignVCenter
    font.pixelSize: 300
    color: 'white'

    signal qmlSignal(string msg)
    onEditingFinished: qmlSignal(text)  //This works
  }
}

I am trying to use the above TextInput element in another qml file like below:

SomeOtherPage.qml

Column {
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.margins: theme.defaultMargin

    MyTextField {
        id: textfield1
        objectName: "textfield1"
        anchors.left: parent.left
        anchors.right: parent.right
        text: qsTr("some text")

       signal qmlSignal11(string msg)
       onEditingFinished: qmlSignal11(text)  //This doesn't work !!
    }

    MyTextField {
        id: textfield2
        objectName: "textfield2"
        anchors.left: parent.left
        anchors.right: parent.right
        text: qsTr("some other text")

       signal qmlSignal22(string msg)
       onEditingFinished: qmlSignal22(text)  //This doesn't work !!
    }
}      

InMyTextField blocks, QML doesn't allow me to use onEditingFinished at all. It complains Cannot assign to non-existent property "onEditingFinished" when I run the app.

If I handle onEditingFinished from the parent TextInput I created, it works fine & sends the signal to my C++ class. But I am trying to use onEditingFinished in textfield1 & textfield2. Qml reports that onEditingFinished property is not available. How I can make onEditingFinished available in textfield1 & textfield2 so that I send the text of each unique textfield I create.


Solution

  • Only the root element, its properties, signals, and methods, are visible from the outside of MyTextField.qml. Just like you already alias a few properties of the inner myTextField, you must also forward the signals you want to use from the outside:

    MyTextField.qml

    import QtQuick 2.5
    import QtQuick.Controls 1.4
    
    Item {
        id: root
        ...
        signal editingFinished() // <==
        ...
        TextField {
            id: myTextField
            ...
            onEditingFinished: root.editingFinished() // <==
        }
    }