Python如何修改单列QVBoxLayout为多列?替换 QWidget 的布局并不那么简单,将另一个对象分配给存储其他布局引用的变量。

self.layout = Foo()
widget.setLayout(self.layout)
self.layout = Bar()

对象与变量不同,对象本身是执行操作的实体,但变量只是存储对象引用的地方。例如,对象可能是人,并变量我们的名字,所以如果他们改变我们的名字,并不意味着他们改变我们作为一个人。

解决方案是使用sip.删除删除Q布局,然后设置新的布局:

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import (
    QApplication,
    QHBoxLayout,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QWidget,
)
import sip
class TestCase(QMainWindow):
    def __init__(self):
        super().__init__()
        test = QWidget()
        self.setCentralWidget(test)

        layout = QVBoxLayout(test)
        for i in range(10):
            temp_btn = QPushButton(str(i))
            temp_btn.pressed.connect(self.multi_col)
            layout.addWidget(temp_btn)
    @pyqtSlot()
    def multi_col(self):
        cols = [QVBoxLayout(), QVBoxLayout()]
        old_layout = self.centralWidget().layout()
        while old_layout.count():
            child = old_layout.takeAt(0)
            widget = child.widget()
            if widget is not None:
                old_layout.removeItem(child)
                cols[0].addWidget(widget)
                cols[1], cols[0] = cols[0], cols[1]
        sip.delete(old_layout)
        lay = QHBoxLayout(self.centralWidget())
        lay.addLayout(cols[0])
        lay.addLayout(cols[1])
def main():
    app = QApplication(sys.argv)
    window = TestCase()
    window.show()
    app.exec_()
if __name__ == "__main__":
    main()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。