问题描述
我有
widget = QtWidgets.Widgets()
layout = QtWidgets.QVBoxLayout(parent=widget)
现在在某些情况下,我想将 QVBoxLayout
更改为 QHBoxLayout
,如果可能的话,我想在创建后执行此操作。也就是说,无需从一开始就简单地创建 QHBoxLayout
。
我试过使用
layout.adoptLayout(QtWidgets.QHBoxLayout())
但这只是返回 True
,并不会改变实际布局。
解决方法
注意: adoptLayout/(
是一个不应公开的内部方法,所以我认为它是一个错误,因为它也没有记录。
要实现方向的改变,可以使用 QBoxLayout 类:
from PySide2 import QtCore,QtWidgets
if __name__ == "__main__":
app = QtWidgets.QApplication()
widget = QtWidgets.QWidget()
lay = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.TopToBottom,widget)
for i in range(4):
button = QtWidgets.QPushButton(f"button {i}")
lay.addWidget(button)
widget.show()
def on_timeout():
direction = (
QtWidgets.QBoxLayout.TopToBottom
if lay.direction() == QtWidgets.QBoxLayout.LeftToRight
else QtWidgets.QBoxLayout.LeftToRight
)
lay.setDirection(direction)
timer = QtCore.QTimer(interval=1000,timeout=on_timeout)
timer.start()
app.exec_()