【问题标题】:PyQT: adding to QAbstractItemModel using a buttonPyQT:使用按钮添加到 QAbstractItemModel
【发布时间】:2015-07-24 19:04:57
【问题描述】:

我正在尝试使用 QAbstractItemModel 实现 TreeView。我想设置一个空模型,然后使用按钮向模型中添加一个项目。

这似乎比我想象的要复杂得多!我已经修改了 Lib\site-packages\PyQt4\examples\itemviews\simpletreemodel\simpletreemodel.pyw 中的 QAbstractItemModel 示例的自定义实例。

我不想一次性设置模型,而是逐步构建它。

当我单击按钮时,我收到一条消息,显示流程方法正在执行,但模型没有更新。

任何关于它为什么不工作的指针将不胜感激!

from PyQt4 import QtGui, QtCore
import sys

class myWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.resize(500, 400)

        #Tree Widget
        self.treeView = QtGui.QTreeView(self)

        #Model
        self.model = TreeModel()                    
        self.treeView.setModel(self.model)

        # Button
        self.button = QtGui.QPushButton(self)
        self.button.setText('Add Item')    
        self.button.clicked.connect(self.process)

        # Add to Layout    
        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.addWidget(self.button,0,0)
        self.gridLayout.addWidget(self.treeView,1,0)

     def process(self):
        print "here"        
        newItem = TreeItem(["bob","bob","bob"],self.model.rootItem)       
        self.model.rootItem.appendChild(newItem) 

class TreeItem(object):
    def __init__(self, data, parent=None):
        self.parentItem = parent
        self.itemData = data
        self.childItems = []

    def appendChild(self, item):
        self.childItems.append(item)

    def child(self, row):
        return self.childItems[row]

    def childCount(self):
        return len(self.childItems)

    def columnCount(self):
        return len(self.itemData)

    def data(self, column):
        try:
            return self.itemData[column]
        except IndexError:
            return None

    def parent(self):
        return self.parentItem

    def row(self):
        if self.parentItem:
            return self.parentItem.childItems.index(self)
        return 0

class TreeModel(QtCore.QAbstractItemModel):
    def __init__(self, parent=None):
        super(TreeModel, self).__init__(parent)
        self.rootItem = TreeItem(("Model", "Status","Location"))

    def columnCount(self, parent):
        if parent.isValid():
            return parent.internalPointer().columnCount()
        else:
            return self.rootItem.columnCount()

    def data(self, index, role):
        if not index.isValid():
            return None

        if role != QtCore.Qt.DisplayRole:
            return None

        item = index.internalPointer()

        return item.data(index.column())

    def flags(self, index):
        if not index.isValid():
            return QtCore.Qt.NoItemFlags

        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self.rootItem.data(section)

        return None

    def index(self, row, column, parent):
        if not self.hasIndex(row, column, parent):
            return QtCore.QModelIndex()

        if not parent.isValid():
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()

        childItem = parentItem.child(row)
        if childItem:
            return self.createIndex(row, column, childItem)
        else:
            return QtCore.QModelIndex()

    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()

        childItem = index.internalPointer()
        parentItem = childItem.parent()

        if parentItem == self.rootItem:
            return QtCore.QModelIndex()

        return self.createIndex(parentItem.row(), 0, parentItem)

    def rowCount(self, parent):
        if parent.column() > 0:
            return 0

        if not parent.isValid():
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()

        return parentItem.childCount()

if __name__ == "__main__":
    app = QtGui.QApplication.instance() # checks if QApplication already exists 
    if not app: # create QApplication if it doesnt exist 
        app = QtGui.QApplication(sys.argv)
    # Window
    window = myWindow()                    
    window.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 如果您手动将数据注入模型 (self.model.rootItem.appendChild(newItem)),则模型永远不会收到更改通知,因此视图也不会收到通知(尽管您最终可能会在鼠标悬停后看到它或触发视图调用模型上的data 的其他事件)。您应该在模型中添加一个新方法来接受和插入数据并在这样做之后调用self.dataChanged.emit(...)
  • 你应该看看QStandardItemModel,它可能更容易实现你想要的。
  • 根据文档使您的模型可编辑,您应该添加 setData 方法。在您的情况下,您还需要方法 insertRows、removeRows、inesrtColumns、removeColumns。 Doc.
  • 感谢您的建议 - 我会告诉您我的进展情况。

标签: pyqt pyqt4


【解决方案1】:

使用 QStandardItemModel 是一种享受!

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.resize(500, 400)

        #Tree Widget
        self.treeView = QTreeView()        

        #Model        
        self.model = QStandardItemModel()
        self.treeView.setModel(self.model)

        # Button
        self.button = QPushButton()
        self.button.setText('Add Item')    
        self.button.clicked.connect(self.addChildClick)

        # Add to Layout    
        self.gridLayout = QGridLayout(self)
        self.gridLayout.addWidget(self.button,0,0)
        self.gridLayout.addWidget(self.treeView,1,0)

    def addChildClick(self):        
        selection = self.treeView.selectedIndexes() 
        text = "bob"
        item = QStandardItem(text)

        # if nothing selected parent is model        
        if selection == []:        
            parent = self.model

        else: # Otherwise parent is what is selected
            s = selection[0] # Handling multiple selectons            
            parent = self.model.itemFromIndex(s)

        parent.appendRow(item)

        #cleanup        
        self.treeView.expandAll()
        self.treeView.clearSelection()

if __name__ == "__main__":
    app = QApplication.instance() # checks if QApplication already exists 
    if not app: # create QApplication if it doesnt exist 
        app = QApplication(sys.argv)

    # Window
    window = Window()                    
    window.show()
    app.exec_()

【讨论】:

  • 谢谢,伙计!很难相信这件事,应该是微不足道的发现,隐藏得如此之好......你完整的代码示例让我再次走上正轨!
猜你喜欢
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2011-11-16
  • 2014-03-28
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多