28

I want to create some tabs, and I read this answer: How to add a tab in PySide

I use the code in the answer and made some changes. Cause my code has to read some files and get the name of my tabs from those file, so that I add a for loop in my code. And here is my code.

from PySide import QtCore, QtGui
import sys
import dflash_controller as con

if __name__ == "__main__":
    list = [['a', 3], ['b', 4], ['c', 5], ['d', 6]]
    app = QtGui.QApplication(sys.argv)
    wid = QtGui.QWidget()
    grid = QtGui.QGridLayout(wid)
    wid.setLayout(grid)

    # setting the inner widget and layout
    grid_inner = QtGui.QGridLayout(wid)
    wid_inner = QtGui.QWidget(wid)
    wid_inner.setLayout(grid_inner)

    # add the inner widget to the outer layout
    grid.addWidget(wid_inner)

    # add tab frame to widget
    wid_inner.tab = QtGui.QTabWidget(wid_inner)
    grid_inner.addWidget(wid_inner.tab)

    # create tab


    for i, index in enumerate(list[0:]):
        new_tab = QtGui.QWidget(wid_inner.tab)
        grid_tab = QtGui.QGridLayout(new_tab)
        grid_tab.setSpacing(10)
        wid_inner.tab.addTab(new_tab, index[0])
        new_tab.setLayout(grid_tab)


    wid.show()
    app.exec_()

It really shows up my tabs. However, I met a warning: QLayout: Attempting to add QLayout "" to QWidget "", which already has a layout Since this tab code just a part of the whole code, the problem will block the data flow. And I have no idea what's wrong with it. I searched for answers, but other answer aren't written in python.

If anyone can help me, thanks in advance.

4

1 回答 1

45

当您通过将小部件QLayout传递给构造函数将其指定为 a 的父级时,布局将自动设置为该小部件的布局。在您的代码中,您不仅要这样做,而且还要显式调用setlayout(). 当传递的小部件相同时,这没有问题。如果它们不同,你会得到一个错误,因为 Qt 试图将第二个布局分配给你已经有一个布局集的小部件。

您的问题在于以下几行:

grid_inner = QtGui.QGridLayout(wid)
wid_inner = QtGui.QWidget(wid)

在这里,您设置widgrid_inner. Qt 想要设置grid_inner为 的布局wid,但wid已经有了上面设置的布局。将以上两行更改为此将解决您的问题。您可以删除调用,setLayout()因为它们是多余的。

wid_inner = QtGui.QWidget(wid)
grid_inner = QtGui.QGridLayout(wid_inner)

使用一种方法或另一种方法来设置布局以避免混淆。

将小部件分配为父级:

widget = QtGui.QWidget()
layout = QGridLayout(widget)

显式设置布局:

widget = QtGui.QWidget()
layout = QGridLayout()
widget.setLayout(layout)
于 2014-08-22T16:12:13.333 回答