0
votes

In QtCreator I added a Tree Widget with two columns to my canvas. This created the XML as follows:-

 <widget class="QTreeWidget" name="postgresTree">
         <property name="geometry">
          <rect>
           <x>20</x>
           <y>10</y>
           <width>851</width>
           <height>471</height>
          </rect>
         </property>
         <property name="styleSheet">
          <string notr="true"/>
         </property>
         <property name="lineWidth">
          <number>1</number>
         </property>
         <property name="allColumnsShowFocus">
          <bool>false</bool>
         </property>
         <property name="columnCount">
          <number>2</number>
         </property>
         <column>
          <property name="text">
           <string notr="true">Schema</string>
          </property>
         </column>
         <column>
          <property name="text">
           <string notr="true">Table</string>
          </property>
         </column>

I then populated this with:-

  QSqlQuery query;
    query.exec("SELECT schema_name FROM information_schema.schemata");

    while(query.next()) {
        QString schema = query.value(0).toString();

        QTreeWidgetItem *schema_branch = new QTreeWidgetItem(ui->postgresTree);
        schema_branch->setText(0,schema);
        schema_branch->setText(1,QString("Table"));

        //Get table list for schema
        QSqlQuery table_query;
        table_query.exec(QString("SELECT tablename FROM pg_tables where schemaname = '%1'").arg(schema));
        while(table_query.next()) {
            QString table = table_query.value(0).toString();
            QTreeWidgetItem *table_branch = new QTreeWidgetItem(ui->postgresTree);
            table_branch->setText(1,table);
            schema_branch->addChild(table_branch);
        }

        ui->postgresTree->addTopLevelItem(schema_branch);
    }

This works but gives me a fixed layout in my tree without the expand/collapse handles. I want to be able to view this tree with the tables column collapsed and expand/collapse controls showing. How do I do this?

enter image description here

1

1 Answers

1
votes

Try changing table_branch to take schema_branch as the parent.

QTreeWidgetItem *table_branch = new QTreeWidgetItem(schema_branch);

Then you also won't need to call addChild.

Calling addTopLevelItem might not be necessary either because you are already giving the tree itself as the parent which should be sufficient.

ui->postgresTree->addTopLevelItem(schema_branch);