Search code examples
pythonqmlpython-3.5pyside2qt5.9

Registering a Python list property to QML in pyside2


I'm trying to load a spreadsheet and pass a list of the worksheets back to my QML interface. But I'm unable to find a way to provide a list(and later a dictionary) back to the QML script.

Here's my QML:

FileDialog {
    id: openDialog
    title: "Open spreadsheet"
    nameFilters: [ "Excel files (*.xls *.xlsx)", "All files (*)" ]
    selectedNameFilter: "Excel files (*.xls *.xlsx)"
    onAccepted: {
        file.load(fileUrl)
        console.log(file.name)
        console.log(file.sheetnames)
    }
    onRejected: {
        console.log("Rejected")
    }
}

Here's the my python class:

class File(QtCore.QObject):

    def __init__(self, *args, **kwargs):
        super(File, self).__init__(*args, **kwargs)
        self.__filename = ""
        self.__sheetnames = list()

    @QtCore.Slot(str)
    def load(self, filename):
        self.__filename = re.sub(r'^[a-zA-Z]+:/+', '', filename)

        # Load the worksheet using openpyxl.
        try:
            workbook = openpyxl.load_workbook(filename=self.__filename)
        except openpyxl.utils.exceptions.InvalidFileException as exception:
            # Todo: write code to pass error to the user.
            print('Invalid File')
            return

        self.__sheetnames = workbook.sheetnames
        print(workbook.sheetnames)

    def set_filename(self):
        return self.__filename

    def get_filename(self, name):
        self.__filename = name

    def get_sheetnames(self):
        return self.__sheetnames

    def set_sheetnames(self, names):
        self.__sheetnames = names

    name = QtCore.Property(str, set_filename, get_filename)
    sheetnames = QtCore.Property(list, get_sheetnames, set_sheetnames)

When I open a spreadsheet, the output is:

['Sheet1']
qml: C:/path/to/my/spreadsheet.xlsx
qml: QVariant(PySide::PyObjectWrapper)

The first line shows that python has the list correct, in the second my script in the QML is successfully getting a string property, but the third isn't getting the list property properly.


Solution

  • You have to use QVariantList instead of list, besides the use of regular expressions may fail, in my case I use Linux and I generate problems, so the correct thing to do is to use QUrl:

    class File(QtCore.QObject):
        filenameChanged = QtCore.Signal()
        sheetnamesChanged = QtCore.Signal()
    
        def __init__(self, *args, **kwargs):
            super(File, self).__init__(*args, **kwargs)
            self.__filename = ""
            self.__sheetnames = list()
    
        @QtCore.Slot(str)
        def load(self, filename):
            self.__filename = QtCore.QUrl(filename).toLocalFile()
            # Load the worksheet using openpyxl.
            try:
                workbook = openpyxl.load_workbook(filename=self.__filename)
            except openpyxl.utils.exceptions.InvalidFileException as exception:
                # Todo: write code to pass error to the user.
                print('Invalid File')
                return
    
            self.__sheetnames = workbook.sheetnames
            print(workbook.sheetnames)
    
        @QtCore.Property(str, notify=filenameChanged)
        def filename(self):
            return self.__filename
    
        @filename.setter
        def get_filename(self, name):
            if name == self.__filename:
                return
            self.__filename = name
            self.filenameChanged.emit()
    
        @QtCore.Property('QVariantList', notify=sheetnamesChanged)
        def sheetnames(self):
            return self.__sheetnames
    
        @sheetnames.setter
        def set_sheetnames(self, names):
            if names == self.__sheetnames:
                return
            self.__sheetnames = names[:]
            self.sheetnamesChanged.emit()
    

    Output:

    ['Periodic Table']
    qml: /home/eyllanesc/Downloads/Ultimate Periodic Table1.xlsx
    qml: [Periodic Table]