Pergunta

Estou criando uma subclasse de QAbstractItemModel a ser exibido em um QTreeView.

Meu index() e parent() A função cria o QModelIndex usando o QAbstractItemModel função herdada createIndex e fornecendo o row, column, e data precisava. Aqui, para fins de teste, os dados são uma string python.

class TestModel(QAbstractItemModel):
    def __init__(self):
        QAbstractItemModel.__init__(self)

    def index(self, row, column, parent):
        if parent.isValid():
            return self.createIndex(row, column, "bar")
        return self.createIndex(row, column, "foo")

    def parent(self, index):
        if index.isValid():
            if index.data().data() == "bar":                          <--- NEVER TRUE
                return self.createIndex(0, 0, "foo")
        return QModelIndex()

    def rowCount(self, index):
        if index.isValid():
            if index.data().data() == "bar":                          <--- NEVER TRUE
                return 0
        return 1

    def columnCount(self, index):
        return 1

    def data(self, index, role):
        if index.isValid():
            return index.data().data()                                <--- CANNOT DO ANYTHING WITH IT
        return "<None>"

Dentro do index(), parent(), e data() funções que preciso para recuperar meus dados. Vem como um QVariant. Como faço para obter meu objeto Python de volta do qVariant?

Foi útil?

Solução 2

O principal é usar internalPointer() diretamente no QModelIndex, não lidar com o QVariant de forma alguma.

class TestModel(QAbstractItemModel):
    def __init__(self, plan):
        QAbstractItemModel.__init__(self)

    def index(self, row, column, parent):
        if not parent.isValid():
            return self.createIndex(row, column, "foo")
        return self.createIndex(row, column, "bar")

    def parent(self, index):
         if index.internalPointer() == "bar":
            return self.createIndex(0, 0, "foo")
        return QModelIndex()

    def rowCount(self, index):
        if index.internalPointer() == "bar":
            return 0
        return 1

    def columnCount(self, index):
        return 1

    def data(self, index, role):
        if role == 0:  # Qt.DisplayRole
            return index.internalPointer()
        else:
            return None

Outras dicas

Você já tentou isso?

my_python_object = my_qvariant.toPyObject()

http://pyqt.sourceforge.net/docs/pyqt4/qvariant.html#topyObject (Apenas por completude, mas não há muito o que ver lá ...)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top