你如何在 PySide 中使用 layout.adoptLayout(layout)?

问题描述

我有

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_()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...