2012-08-05 53 views
1

是否有一种自动方法可以用来将QVariantMap的内容设置为QTreeView,或者我必须为此定义一个模型?将QTreeView设置为QVariantMap内容

在此先感谢

+0

你想让你的地图充当数据源,还是只是一个临时容器?您可以使用标准模型并将数据加载到其中...但是如果您想直接使用地图,则必须将其包装到模型中。 – jdi 2012-08-05 02:58:43

+0

我只是想将我的地图中的数据显示在树形视图中 – Ameen 2012-08-05 03:01:23

回答

0

请原谅的事实,我必须提供在python(PyQt4中)我的例子。有两种方法可以解决您的问题。您可以将您的QVariantMap数据推送到与您的视图相关的模型中,该模型可以独立管理,或者您必须定义自己的模型,将QVariantModel作为数据源来包装以主动驱动数据。

我正在提供一个将数据推送到标准模型的简单示例。在python中没有QVariantMap,所以我使用了关键int => QVariant字符串值的字典。

class View(QtGui.QWidget): 

    def __init__(self): 
     super(View,self).__init__() 

     self.layout = QtGui.QVBoxLayout(self) 
     self.table = QtGui.QTableView() 
     self.layout.addWidget(self.table) 

     self.button = QtGui.QPushButton("Update") 
     self.layout.addWidget(self.button) 

     # Using a normal QStandardItemModel and setting 
     # it on the table view. 
     self.model = QtGui.QStandardItemModel(self) 
     self.table.setModel(self.model) 

     self.button.clicked.connect(self.populate) 

    def populate(self): 
     # no QVariantMap in PyQt4. Creating a dictionary on the fly 
     # of int key => QVariant string... {0: QVariant('foo'), ...} 
     variantMap = {i:QtCore.QVariant('foo') for i in xrange(10)} 

     col = 0 
     row = 0 
     # loop over each element in your map, and add a QStandardItem 
     # at a specific row/column 
     for name, val in variantMap.iteritems(): 
      item = QtGui.QStandardItem(val.toString()) 
      self.model.setItem(row, col, item) 
      row += 1 

我创建了一个QTableView和一个QStandardItemModel。然后我在视图上设置模型。我创建了一个连接到填充插槽的按钮。当这个插槽被调用时,我创建一个“QVariantMap”类型的对象来模拟你的数据容器。然后我遍历该容器的内容,并为每个单元格创建一个QStandardItem。我将该项目设置到特定列和行的模型中。在这个例子中,我只使用了第0列,并添加了行。

我希望这个例子很容易转化为你的情况。