I have the source code follow as below:
I have 2 qml files. The second qml file has been called from the maim.qml file. I want to get the text from the second qml file using the signal and slot method.
main.qml file:
ApplicationWindow {
id: applicationWindow1
StackLayout {
id: swipeView
anchors.left: sideBar.right
anchors.right: parent.right
anchors.bottom: tabBar.top
anchors.top: parent.top
currentIndex: tabBar.currentIndex
firstpage{}
Secondpage{}
}
TabBar {
id: tabBar
height: 42
anchors.bottom: parent.bottom
anchors.left: sideBar.right
anchors.right: parent.right
currentIndex: swipeView.currentIndex
TabButton {
text: qsTr("firstpage")
}
TabButton {
text: qsTr("Secondpage")
}
}
secondpage.qml
Item{
signal submitTextField(string text)
// this function is our QML slot
function setTextField(text){
console.log("setTextField: " + text)
textField1.text = text
}
visible: true
width: 360
height: 360
TextField {
id: textField1
x: 31
y: 169
placeholderText: qsTr("Enter some text...")
}
Button {
x: 193
y: 167
text: qsTr("Uppercase me!")
onClicked:
// emit the submitTextField signal
submitTextField(textField1.text)
}
}
code C++ : HandleTextField.h file
class HandleTextField : public QObject
{
Q_OBJECT
public:
explicit HandleTextField(QObject *parent = 0) {}
signals:
void setTextField(QVariant text);
public slots:
void handleSubmitTextField(const QString& in)
{
qDebug() << "c++: HandleTextField::handleSubmitTextField:" << in;
emit setTextField(in.toUpper());
}
}
main.cpp file
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQuickView view;
view.setSource(QUrl(QStringLiteral("qrc:/secondpage.qml")));
QObject *item = view.rootObject();
HandleTextField handleTextField ;
QObject::connect(item,SIGNAL(submitTextField(QString)),&handleTextField ,SLOT(handleSubmitTextField(QString)));
QObject::connect(&handleTextField ,SIGNAL(setTextField(QVariant)),item,SLOT(setTextField(QVariant)));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
-->> When I press the button, there is no action. Please tell me what I'm doing wrong here.
Thanks