QTreeWidget Collaps/Expand 项

QTreeWidget Collaps/Expand items

在 QtCreator 中,我向 canvas 添加了一个包含两列的树形小部件。这创建了 XML 如下:-

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

然后我填充了这个:-

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

这可行,但在没有 expand/collapse 句柄的情况下为我的树提供了固定布局。我希望能够在表格列折叠并显示 expand/collapse 控件的情况下查看此树。我该怎么做?

尝试更改 table_branch 以将 schema_branch 作为父级。

QTreeWidgetItem *table_branch = new QTreeWidgetItem(schema_branch);

那么你也不需要调用 addChild。

可能也没有必要调用 addTopLevelItem,因为您已经将树本身作为父级,这应该足够了。

ui->postgresTree->addTopLevelItem(schema_branch);