zonzely
zonzely

Reputation: 395

Qt-how to connect a function to a signal in qml with python? using QQmlApplicationEngine

this is the qml file. "main.qml"

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

ApplicationWindow{
    visible:true
    width:640
    height:480
    id:window
    title:asTr("editor")

    signal show(string text)



    TextArea{
        text:"hello"
        onTextChanged:show(text);
    }

}

this is the python code . "main.py"

import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine

def show(text):
    print(text)


if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()
  engine.load('main.qml')
  win = engine.rootObjects()[0]
  win.show()
  sys.exit(app.exec_())

I want to connect the signal "show" in main.qml to the slot "show" in main.py. How can I do this?

Upvotes: 1

Views: 1799

Answers (1)

mata
mata

Reputation: 69012

First and most important: don't call your signal show, show already is a slot of the QWindow. If you change the name to something else, then you can simply connect the signal defined in qml in your python code:

qml:

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

ApplicationWindow{
    visible:true
    width:640
    height:480
    id:window
    title: "editor"

    signal textUpdated(string text)


    TextArea{
        text:"hello"
        onTextChanged: textUpdated(text);
    }

}

python:

import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine

def show(text):
    print(text)


if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()
  engine.load('main.qml')
  win = engine.rootObjects()[0]
  win.textUpdated.connect(show)
  win.show()
  sys.exit(app.exec_())

Upvotes: 2

Related Questions