Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert QJSValue to Python list in Python and QML?

Tags:

python

qml

pyqt5

I hava a Python file ang a QML file. i get value in Python file from QML, and the type of value is QJSValue , i want to convert it to Python list. i don't know how to do it.

following is my code.

test.python

#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtCore import  QUrl, QObject, pyqtSlot,QVariant
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QJSValue

class MyMain(QObject):

    @pyqtSlot(QJSValue)
    def get_value(self,value):
        print(value,type(value))


if __name__ == '__main__':
    path = 'test.qml'
    app = QApplication([])
    view = QQuickView()
    con = MyMain()
    context = view.rootContext()
    context.setContextProperty("con",con)
    view.engine().quit.connect(app.quit)
    view.setSource(QUrl(path))
    view.show()
    app.exec()

test.qml

import QtQuick 2.4
import QtQuick.Controls 1.3

Button {
        text: "click"
        onClicked: {
               con.get_value([{"name":"a","text":"1"},{"name":"b","text":"2"}]) 
            }
    }
like image 466
zonzely Avatar asked Nov 16 '25 11:11

zonzely


1 Answers

I realize this question is extremely old, but I thought I'd post how I came to the solution in case someone else stumbles upon it via Google. While it isn't technically a direct conversion to a python list, what I found useful was to do myQJSValueInstance.toVariant() which converts the instance to a QVariant. I could then use the object as needed (e.g., iterating through it as if it were a normal python list).

like image 95
GPhilo Avatar answered Nov 18 '25 21:11

GPhilo