python - 在布局中移动小部件 pyqt

标签 python pyqt pyqt4 qlayout

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

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

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

关于python - 在布局中移动小部件 pyqt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889080/

相关文章:

python企业防火墙代理407需要身份验证错误

python - numpy:对操作结果执行 "any"或 "all"的有效方法

python - IQtNetwork.QHttp请求凭证问题

python - PyQt4 - 小部件未显示

python - 如何在 pyqt 中对齐右下角的按钮?

python - 使用 PyQT QDialogs (Python) 的视频播放器

python - 如何修复 google 脚本中的 "Login information disallowed"错误?

python - 为什么处理随机列表比处理有序列表快得多?

python-3.x - 在另一台计算机上运行卡住的 pyqt 应用程序时不显示图像

python - 如何创建正确跨越多个页面的可打印列表