QT开发中文网

Can I have a QTreeWidget with topLevelItem being a list of Widget?

Yes, you can have a QTreeWidget with a top-level item that contains a list of widgets. Here’s an example code snippet that demonstrates how to achieve this:

from PyQt5.QtWidgets import QApplication, QTreeWidgetItem, QWidget, QVBoxLayout, QLabel

app = QApplication([])
tree = QTreeWidget()
tree.setHeaderLabels(['Name', 'Description'])

# Create a top-level item
top_level_item = QTreeWidgetItem(tree)
widget_list = []

# Add widgets to the list
for i in range(3):
    widget = QWidget()
    layout = QVBoxLayout(widget)
    layout.addWidget(QLabel(f"Widget {i}"))
    layout.addWidget(QLabel(f"This is widget {i} added to the tree"))
    widget_list.append(widget)

# Set the top-level item widget
top_level_widget = QWidget()
top_level_layout = QVBoxLayout(top_level_widget)
for widget in widget_list:
    top_level_layout.addWidget(widget)
tree.setItemWidget(top_level_item, 0, top_level_widget)

# Show the tree
tree.show()
app.exec_()

In this code snippet, we create a new QTreeWidget and set its header labels. We then create a new QTreeWidgetItem object as our top-level item and initialize an empty list called widget_list.

We then loop over some range (in this case 3) and create three new QWidget objects using a vertical box layout (QVBoxLayout). We add two QLabel widgets to each of these new widgets: one that displays the label “Widget x”, where x is the current iteration number (0 through 2), and another that displays some sample text.

After creating these widgets, we add them to our widget_list.

Next, we create another new widget using a vertical box layout (QVBoxLayout) called top_level_widget. We loop over our widget_list, adding each one to the top_level_layout using addWidget(). Finally, we call setItemWidget() with our top-level item and our top_level_widget as its content.

When running this code snippet, you should see something like this:

Example UI with Tree Widget containing List of Widgets

As you can see, we now have a tree widget with a top-level item that contains a list of widgets. Each widget has its own label and description.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://qt.0voice.com/?id=2887

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?