Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8414497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T01:11:17+00:00 2026-06-10T01:11:17+00:00

I am making a QTreeWidget from a XML file. The XML looks like below

  • 0

I am making a QTreeWidget from a XML file. The XML looks like below and I want to make a tree of the names:

<root>
    <f name='foo'>bar
        <f name='foo2'>baz</f>
    </f>
</root>

At the moment I am using the following code to do so (somewhat simplified code):

import lxml.etree as et

#...

self.xml = et.XML(filters.filtersxml)
self.tree_widget = QTreeWidget(parent)

def add_items(parent, xmlroot):
    for i in xmlroot.getchildren():
        item = QTreeWidgetItem(parent, [i.get('name')])
        if len(i.getchildren()) != 0:
            add_items(item, i)

add_items(self.tree_widget, self.xml)

I actually have two questions about this:

  1. Main question: Is there some way to select the first item in the tree, foo in this case. I tried to do something with setCurrentItem() and setCurrentIndex(), but couldn’t get it to work. I have googled a bit about it, but all the solutions that I found work with models.
  2. (Optional) Is this recursive function a good approach to do this, or is there a better way?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T01:11:18+00:00Added an answer on June 10, 2026 at 1:11 am

    Recursive is good, would keep it that way, and in answer to your main question just do:

    # after all your code
    add_items(self.tree_widget, self.xml)
    
    # select the root item
    self.tree_widget.setCurrentItem(self.tree_widget.topLevelItem(0))
    

    You just have to make sure that the item has already been added to the tree when you call setCurrentItem – otherwise it won’t really work. Some methods require the item to already be associated to a tree (like setExpanded and setSelected)

    Edit

    To build up recursively without affecting the tree, you can do:

    import lxml.etree as et
    
    #...
    
    self.xml = et.XML(filters.filtersxml)
    self.tree_widget = QTreeWidget(parent)
    
    def add_items(parent, xmlroot):
        output = []
        for i in xmlroot.getchildren():
            item = QTreeWidgetItem(parent, [i.get('name')])
            output.append(item)
            if len(i.getchildren()) != 0:
                add_items(item, i)
        return output
    
    items = add_items(None, self.xml)
    self.tree_widget.addTopLevelItems(items)
    self.tree_widget.setCurrentItem(items[0])
    

    Edit 2: Loading all at once

    And to go a bit further down the rabbit hole, the way that I would personally do this to minimize unnecessary calls and lists as much as possible would be to build the loop the children only once:

    import lxml.etree as et
    
    #...
    
    self.xml = et.XML(filters.filtersxml)
    self.tree_widget = QTreeWidget(parent)
    
    def create_item(parent, xmlroot):
        item = QTreeWidgetItem(parent, [xmlroot.get('name')])
        for xmlchild in xmlroot.getchildren():
           create_item(item, xmlchild)
        return item
    
    items = [create_item(None, xmlchild) for xmlchild in self.xml.getchildren()]
    self.tree_widget.addTopLevelItems(items)
    if ( items ):
        self.tree_widget.setCurrentItem(items[0])
    

    Edit 3: Loading dynamically

    And since it was brought up…a way to dynamically load the children would be to store each level and load them after being expanded:

    import lxml.etree as et
    from PyQt4.QtGui import QTreeWidgetItem
    
    # ...    
    
    class XmlTreeWidgetItem(QTreeWidgetItem):
        def __init__( self, parent, xmlitem ):
            super(MyTreeWidgetItem, self).__init__(parent)
            self.setText(0, xmlitem.get('name'))
            self.setChildIndicatorPolicy(self.ShowIndicator)
    
            self._xmlitem = xmlitem
            self._loaded = False
    
        def loadChildren( self ):
            if ( self._loaded ):
                return
    
            self._loaded = True
            self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
            for xmlchild in self._xmlitem.getchildren():
                XmlTreeWidgetItem(self, xmlchild)
    
    # ...
    
    class SomeClass(QWidget):
        def __init__( self, parent = None ):
            super(SomeClass, self).__init__(parent)
    
            self.tree_widget = QTreeWidget(parent)
    
            xml = et.XML(filters.filtersxml)
            items = [XmlTreeWidgetItem(None, xchild) for xchild in xml.getchildren()]
            self.tree_widget.addTopLevelItems(items)
            if ( items ):
                self.tree_widget.setCurrentItem(items[0])
    
            # create connections
            self.tree_widget.itemExpanded.connect(self.loadItem)
    
        def loadItem( self, item ):
            item.loadChildren()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Making the transition from Vim to gVim, I would like to disable all toolbars
Making a ternary logic table, and I would like to make my own function
im making an application where i have to load my database from html file
making a new jsp and got a mock-up from some analyst. Notice the sections
Making a search result list (like in Google) is not very hard, if you
Making a quick JQuery demo where clicking a table element changes it from black
Making an app where we want to send a photo to a server along
making a thumbnail from video using the picker is straight forward. However, when I
Im making a fairly big game for Mac appstore, and i would like to
Making a migration from 2.8.1 to 2.9.1 found interesting thing. Tried to write this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.