QTreeWidget 中的垂直行间距

Vertical Row spacing in QTreeWidget

我有一个 QTreeWidget,其中填充了自定义小部件。我从外部 API 检索项目类型,它可能是文本值、数值或其他任何值。 根据类型,我为 QTreeWidgetItem 提供了不同的控件。例如 QLabel 用于文本输入,QSpinBox 用于数值等等。

这是通过以下代码完成的:

for (GenApi::INode * poNode : oNodeList)  // iterate over a list of items   which i want to represent in the treewidget 
{
QTreeWidgetItem * poRootItem = new QTreeWidgetItem(poTree); //poTree is a   QTreeWidget
poRootItem->setText(0, poNode->GetDisplayName().c_str());
poTree->addTopLevelItem(poRootItem);                        // add as category

GenApi::NodeList_t oInnerNodes;
poNode->GetChildren(oInnerNodes);

for (GenApi::INode * poInnerNode : oInnerNodes)             // each of those nodes may have innter child nodes
{
    QTreeWidgetItem * poItem = new QTreeWidgetItem();
    CNodeItemBase * poNodeUI = NULL;

    if (GenApi::CIntegerPtr(poInnerNode) != NULL)
        poNodeUI = new CNodeItemInteger(*poInnerNode, poTree);  //CNodeItem... inherits from QWidget and takes the tree as parent

    else if (GenApi::CStringPtr(poInnerNode) != NULL)
        poNodeUI = new CNodeItemString(*poInnerNode, poTree);

    // more possibilities go here....

    if (poNodeUI != NULL)
    {
        poRootItem->addChild(poItem);
        poItem->setText(0, poNodeUI->GetDisplayName().c_str());  // set text of the item
        poTree->setItemWidget(poItem, 1, poNodeUI->m_poControl); // set label/spinbox as widget of the treeitem  
    }
}
}

代码有效,但生成的 TreeWidget 有问题:

生成的 TreeWidgetItem 有很大的间距,这使得 TreeWidget 很难在视觉上 read/iterate。有没有一种快速简便的方法来提供类似 QSizePolicy 的东西来缩小项目?我已经尝试了每一种组合,但到目前为止没有任何效果。

由于您使用的是带布局的小部件,请确保在布局上使用 smaller/appropriate 值调用 setContentsMargins(尽管文档怎么说,默认值是每条边上有六个像素) .