gpt4 book ai didi

python - 如何将小部件放入 PyQt QMdiSubWindow 中

转载 作者:行者123 更新时间:2023-11-30 22:55:07 24 4
gpt4 key购买 nike

抱歉,我的问题可能听起来很愚蠢,但坦白说,我在互联网上花了很多时间试图找出如何将小部件s添加到 QMdiSubWindow,我的意思是多个小部件 不仅仅是一个小部件(这对我来说非常重要..我需要我的子窗口包含多个小部件而不是单个小部件)。

例如,我想将此小部件和布局添加到我的子窗口:

QVbox 包含 QlineEdit 和按钮,QHbox 包含按钮 ...

it doesn't matter if you show me how i could do it using the above example, what really matter is to show me how no matter what example you use

注意:请使用OOP和Python而不是c++

最佳答案

小部件和布局的层次结构应始终遵循

widget -> layout -> widget -> layout -> widget -> ...

其中每个小部件只能有一个布局,但每个布局可以包含多个小部件(请注意,为简单起见,上面只显示每个布局一个小部件)。

因此,您需要做的是创建一个包含布局的小部件,并且该布局包含 QPushButton 和 QLineEdit`。例如:

# construct the top level widget
widget = QWidget()
# construct the top level layout
layout = QVBoxLayout(widget)

# create the widgets to add to the layout
button = QPushButton('My Button')
lineedit = QLineEdit()

# add the widgets to the layout
layout.addWidget(button)
layout.addWidget(lineedit)

# set the layout on the widget
widget.setLayout(layout)
# we now have a single widget that contains a layout and 2 widgets

这允许您有效地将多个小部件封装在一个小部件中(这也是许多更复杂的 Qt 小部件在内部创建的方式,例如 QSpinBox)。因此,如果您想要在上面的布局中添加另一个复杂的小部件,您可以再次制作另一个 widget2 = QWidget(),创建一个布局(例如 layout2 = QHBoxLayout(widget2)) ,然后向其中添加多个小部件。完成后,将 widget2 小部件添加到原始布局 (layout.addWidget(widget2))。

希望您现在可以了解如何从任意数量的子小部件和布局构造单个复杂的小部件。

此时,您现在可以将单个小部件设置为现有的QMdiSubWIndow

# now add this widget to the QMdiSubWindow
mdisubwindow.setWidget(widget)

或者,调用 QMdiArea 上的便捷函数来使用小部件创建一个新的 QMdiSubWindow:

mdisubwindow = mdiarea.addSubWindow(widget)

注意:对于您的具体示例,您实际上不需要构造 widget2 来封装 QHBoxLayout。您可以通过调用 layout.addLayout(layout2)QHBoxLayout(在上面的粗略示例中为 layout2)直接添加到原始布局。然而,这更多的是一种特殊情况,一旦您开始创建自己的小部件类以重用代码,上面的交替小部件和布局封装的一般原则就更具有普遍性。

关于python - 如何将小部件放入 PyQt QMdiSubWindow 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com