我有一个 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 难以在视觉上阅读/迭代。有没有一种快速简便的方法来提供类似 QSizePolicy 的东西来缩小项目?我已经尝试了每一种组合,但到目前为止没有任何效果。
最佳答案
由于您使用的是带布局的小部件,请务必调用 setContentsMargins
在具有较小/适当值的布局上(默认值是每个边缘有六个像素,尽管文档怎么说)。
关于c++ - QTreeWidget 中的垂直行间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37477971/