python - pyside/pyqt : Getting values from dynamically created qlineedits on button clicked

标签 python pyqt pyside qlineedit

我有一个程序可以根据用户输入创建许多 qlineedits 和按钮:

screenshot of GUI

在上面的图像中,在单击变灰的“下一步”按钮后,添加了一个带有按钮的 4 行。现在,我想在单击相应按钮时将用户的输入输入到一个函数中(单击“创建镜头 1!--> 转到一个将“exShot1”作为参数传递的函数)。

问题是我不知道如何在循环中创建每个 qline 和按钮时获取它们的名称。我想我可以在循环中创建唯一变量,但感觉不对。我试过使用 setObjectName 但我不知道如何使用它来调用文本。我也对 Lamdba 进行了一次不成功的尝试(我觉得这可能是正确的方式)我相信这是在用户输入更改时必须获取名称和跟踪的组合。

我已经尝试过 textChanged 并且我让它在循环的最后一个条目上工作但不适用于其他 qlines 和按钮)

相关代码:

while i <= int(seqNum):
    #create each widget
    self.createShotBtn = QtGui.QPushButton("Create Shot %s!" %str(self.shotNumberLst[i-1]))
    self.labelName = QtGui.QLabel(self)
    self.labelName.setText("Enter Name Of Shot %s!" %str(self.shotNumberLst[i-1]))
    self.shotName = QtGui.QLineEdit(self)
    self.shotName.setObjectName("shot"+str(i))

    #add widget to layout
    self.grid.addWidget(self.labelName, 11+shotjump,0)
    self.grid.addWidget(self.shotName,11+shotjump,1)
    self.grid.addWidget(self.createShotBtn, 11+shotjump,2)

    #Press button that makes magic happen
    self.createShotBtn.clicked.connect(???)

    i += 1

编辑:如果用户在所有行上输入输入并按下一个按钮将所有这些输入作为列表或字典传递(每个“镜头”将添加更多行),这也很好

最佳答案

问题是每次运行 self.createShotBtn 的值时,self.labelNameself.shotName 都会被覆盖。

因此在最后一次运行时,它们是固定的,但仅针对最后一次迭代。

相反,您希望在循环中使用局部范围的变量,并可能将其存储在数组中供以后使用。

此代码应该接近您的需要,但我可以看到 self.shotNumberLst(它返回一个数字?)和 shotjump(这是一个 offest,或等于 i) 被声明。

self.shots = []
for i in range(seqNum): # Changed while to for, so you don't need to increment
    #create each widget
    createShotBtn = QtGui.QPushButton("Create Shot %s!" %str(self.shotNumberLst[i-1]))
    labelName = QtGui.QLabel(self)
    labelName.setText("Enter Name Of Shot %s!" %str(self.shotNumberLst[i-1]))
    shotName = QtGui.QLineEdit(self)

    self.shots.append({"button":createShotBtn,
                       "name":shotName)) # Store for later if needed.

    #add widget to layout
    self.grid.addWidget(labelName, 11+shotjump,0)
    self.grid.addWidget(shotName,11+shotjump,1)
    self.grid.addWidget(createShotBtn, 11+shotjump,2)

    #Press button that makes magic happen
    createShotBtn.clicked.connect(self.createShot(i))

#elsewhere
def createShot(self,index):
    print self.shots[index]["name"].text

关于python - pyside/pyqt : Getting values from dynamically created qlineedits on button clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19156999/

相关文章:

python - 如何在 PySide/PyQt 的屏幕中央制作一个小部件?

python - Matplotlib 共享 y 轴 - 一个子图未对齐

python - PyQt4无法导入Qsci

python - 向 Python QProcess 示例添加按钮和单独的窗口

Python QT (PySide) QPushButton 样式表导致 "assertion ' GTK_IS_WIDGET(小部件 )' failed"错误

python - 在 PyQT/PySide 中设置窗口样式?

python - 如何使用 Tensorflow(python) 为 keras model.fit() 创建我自己的数据集?

python - 在 Flask 中寻找 url_for 的倒数

python - 如何在 Windows 10 PC 上创建 Docker 容器以在 Raspberry Pi 4 上运行

python - PyQt如何从布局中移除布局