简体   繁体   中英

QTreeWidget Collaps/Expand items

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?

在此处输入图像描述

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM