python - 在布局中移动小部件 pyqt
问题描述
嗨,我的代码中有按钮,我希望当用户按下插入新按钮时,它会将所有其他按钮移到下方一行并在按下的按钮下方创建一个新按钮这是我的代码
基本上,我正在尝试将布局中的所有按钮移动到下方一行,然后添加新按钮:
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)
解决方案
假设您使用的是 aQVBoxLayout
您必须使用以下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_())
推荐阅读
- scala - 为什么 scala 克隆在 IntelliJ 中显示 AnyRef 错误?
- ios - 为什么 ui 元素以 swift 编程方式在视图控制器之间共享?
- javascript - 承诺“解决”是将对象转换为字符串?
- wpf - 列表框不显示 observablecollection 的内容
- r - 向 NetworkD3 对象添加顶点属性
- ios - 每次呈现时重新加载视图(SwiftUI)
- lua - 在 tarantool 中更改 box.info 字段设置触发器?
- android - Gradle 尝试从错误的存储库下载
- azure - 在 azure 上使用 cert-manager 和 istio 订购证书时出现问题
- javascript - 滑动条如何更改值 vue.js