开发者

setSelected in QTreeWidget

I have a project where I need to change the selection of a tree widget in code. This needs to be done after I clear out the tree and populate it again.

I'm trying to mark the appropriate item as "selected" while I'm adding them. This works for root level nodes. But for child nodes, it doesn't. I need to store the QTreeWidgetItem in another variable and mark it as selected after the tree has been completely populated. Why does this happen?

This does not work:

def refreshTree(self):
    treeObj.clear()
    for item in items:
        temp = QTreeWidgetItem(0)开发者_如何学Go
        for key, val in item.subitems().items():
            childTemp = QTreeWidgetItem(0)
            ...setup text, font, etc...

            if(condition1):
                childTemp.setSelected(True)
            temp.addChild(childTemp)

        if(!condition1 and condition2):
            temp.setSelected(True)

        treeObj.addToplevelItem(temp)

This does:

def refreshTree(self):
    treeObj.clear()
    for item in items:
        temp = QTreeWidgetItem(0)
        for key, val in item.subitems().items():
            childTemp = QTreeWidgetItem(0)
            ...setup text, font, etc...

            if(condition1):
                selTemp = childTemp
            temp.addChild(childTemp)

        if(!condition1 and condition2):
            temp.setSelected(True)
        elif(selTemp):
            selTemp.setSelected(True)
        treeObj.addToplevelItem(temp)


It is not specified in the documentation, but setSelected does nothing if the item hasn't been added to a view yet:

inline void QTreeWidgetItem::setSelected(bool aselect)
{ if (view) view->setItemSelected(this, aselect); }

So, you should either

  • pass treeObj or temp in the constructor of your QTreeWidgetItem to make them part of the view from the start
  • or call addChild/addTopLevelItem before calling setSelected (or other functions like setExpanded...).

I don't know why your second code was even working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜