[SOLVED] Cannot add child items in Root Tree entries



  • Consider the following Addroot and Addchild functions of a QTreeWidget object:

    @void Dialog::AddRoot(QString name, QString Description){

            QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeWidget);
            itm->setText(0,name);
            itm->setText(1,Description);
            ui->treeWidget->addTopLevelItem(itm);
            AddChild(itm,"One", "Hello");
            AddChild(itm,"Two", "World");
    

    }

    void Dialog::AddChild(QTreeWidgetItem *parent, QString name, QString Description){

            QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeWidget);
            itm->setText(0,name);
            itm->setText(1,Description);
            ui->treeWidget->addTopLevelItem(itm);
            parent->addChild(itm);
    

    }
    @

    Running this tree view still shows every entry as a root and not a child, no matter what.

    According to the same online tutorial, to fix this, the author merely replaces
    @QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeWidget);@ with @QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeWidget);@ (Line 13) and it works. I tried the same identical step and it still doesnt fix the problem of only roots showing. I think it has to do with Qt version, is this true? Did the recent releases change the way Tree's are modelled?


  • Lifetime Qt Champion

    Hi,

    In both Add functions, you do a ui->treeWidget->addTopLevelItem.

    Shouldn't AddChild be

    @
    QTreeWidgetItem *itm = new QTreeWidgetItem(parent);
    itm->setText(0,name);
    itm->setText(1,Description);
    @

    ?



  • Hi,

    line 13 should be
    @ QTreeWidgetItem *itm = new QTreeWidgetItem();@
    or
    @ QTreeWidgetItem *itm = new QTreeWidgetItem;@
    not
    @ QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeWidget);@

    and you need to remove line 16.

    so this code must be like this
    @
    void Dialog::AddChild(QTreeWidgetItem *parent, QString name, QString Description){

            QTreeWidgetItem *itm = new QTreeWidgetItem();
            itm->setText(0,name);
            itm->setText(1,Description);
            parent->addChild(itm);
    

    }@



  • Aha, it works when removing line 16.

    Thanks guys.


  • Lifetime Qt Champion

    You're welcome !

    Don't forget to update the thread's title to solved so other forum users may know that a solution has been found.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.