Python 使用for循环将对象添加到QGridLayout
您好,我正在尝试使用python中的For循环将对象添加到Python 使用for循环将对象添加到QGridLayout,python,pyqt5,Python,Pyqt5,您好,我正在尝试使用python中的For循环将对象添加到QGridLayout 在我的例子中,对象是一个QPushButton 网格将以3行为一行 下面是我当前的代码,试图实现这一点 for i in range(shoes): shoebtn = QtWidgets.QPushButton(self.scrollAreaWidgetContents) shoebtn.setMinimumSize(QtCore.QSize(280
QGridLayout
在我的例子中,对象是一个QPushButton
网格将以3行为一行
下面是我当前的代码,试图实现这一点
for i in range(shoes):
shoebtn = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
shoebtn.setMinimumSize(QtCore.QSize(280, 317))
shoebtn.setMaximumSize(QtCore.QSize(280, 317))
shoebtn.setStyleSheet("border:none;\n""background-color: rgb(140, 140, 140);\n""margin-bottom:10px;")
shoebtn.setText("")
shoebtn.setObjectName(f"shoeBtn{i}")
self.gridLayout.addWidget(shoebtn, 0,0,1,1)
我想我知道问题出在哪里了,这是0,0,1,1
在代码的最后一行,我想这是网格上的定位。我真的不知道该怎么计算。有人能帮忙吗?谢谢试试看:
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QGridLayout)
from PyQt5.QtCore import QSize
class Example(QWidget):
def __init__(self):
super().__init__()
self.gridLayout = QGridLayout(self)
shoes = 7
row = 0
column = 0
for i in range(shoes):
if column == 3:
column = 0
row += 1
shoebtn = QPushButton() # (self.scrollAreaWidgetContents)
shoebtn.setFixedSize(QSize(50, 50))
shoebtn.setObjectName(f"shoeBtn{i}")
shoebtn.clicked.connect(lambda _, text=shoebtn.objectName(): print(f'Clicked {text}'))
self.gridLayout.addWidget(shoebtn, row, column)
column += 1
self.setStyleSheet("""
QPushButton {
border: none;
background-color: rgb(140, 140, 240);
margin-bottom: 10px;
}
""")
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
使用
self.gridLayout.addWidget(shoebtn,i,0)
谢谢!!那有帮助