Python 在布局中移动小部件pyqt

Python 在布局中移动小部件pyqt,python,pyqt,pyqt4,qlayout,Python,Pyqt,Pyqt4,Qlayout,嗨,我的代码中有按钮,我想当用户按下“插入新按钮”时,它会将所有其他按钮移到下面一行,并在按下的按钮下方创建一个新按钮这是我的代码 基本上,我正在尝试将布局中的所有按钮移动到下面一行,然后添加新按钮: def Insert_Stage(self) : button = self.sender() idx = self.Layout.indexOf(button) location = self.Layout.getItemPosition(idx) x=loca

嗨,我的代码中有按钮,我想当用户按下“插入新按钮”时,它会将所有其他按钮移到下面一行,并在按下的按钮下方创建一个新按钮这是我的代码

基本上,我正在尝试将布局中的所有按钮移动到下面一行,然后添加新按钮:

def Insert_Stage(self) :
    button = self.sender()
    idx = self.Layout.indexOf(button)
    location = self.Layout.getItemPosition(idx)

    x=location[0]
    z=self.Layout.rowCount()
    print(x,z)
    while(z >x+1):

        items= self.Layout.itemAt(z)
        # setting the item as widget 
        widget=items.widget()
        index= self.Layout.indexOf(widget)
        loc=self.Layout.getItemPosition(index)

        d=loc[0]
        y=loc[1]
        if y!=0:
            #widget.move(d+100,d)
            self.Layout.addWidget(widget,(d+1),1)
        else:
         self.Layout.addWidget(widget,d+1,0)
        z-=1

    stage=QtGui.QPushButton(self)
    stage.setObjectName(button.objectName())
    k=(int(button.objectName()[5:])+1)
    stage.setText('stage%d'%k)
    self.Layout.addWidget(stage,(location[0]+1),0)

假设您使用的是
QVBoxLayout
,则必须使用
insertWidget()
方法:

from PyQt4 import QtCore, QtGui

class Widget(QtGui.QLineEdit):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        lay = QtGui.QVBoxLayout(self)
        for i in range(5):
            btn = QtGui.QPushButton(
                'button {}'.format(i),
                clicked=self.on_clicked
            )
            lay.addWidget(btn)

    @QtCore.pyqtSlot()
    def on_clicked(self):
        btn = self.sender()
        ix = self.layout().indexOf(btn)
        new_btn = QtGui.QPushButton(
            "button {}".format(self.layout().count()),
            clicked=self.on_clicked
        )
        self.layout().insertWidget(ix+1, new_btn)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication.instance()
    if app is None:
        app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

@salaheddine如果我的答案有助于您不要忘记将其标记为正确,如果您不知道如何做,请查看“完成”,谢谢:),它是否适用于网格布局?因为我有错误网格布局没有选择insert@salaheddineQGridLayout没有任何插入方法,因此解决方案非常复杂,因为它将获得按下按钮下的按钮,将它们从布局中移除,使用addWidget设置新按钮,并使用addWidget重新建立移除的按钮。使用QVBoxLayout,解决方案很简单。@salaheddine使用
self.layout().insertWidget(0,new_btn)
,请阅读文档:@eyllanesc是的,我明白了,这很愚蠢,忘记了索引0=第一行,谢谢,尽管这就是为什么我之后删除了我的问题