将通过for循环生成的QLineEdit小部件中的值相加

时间:2019-02-09 08:52:13

标签: python-3.x pyqt5 pyside2

我试图将使用for循环生成的QLineEdit框的值相加。但是,它仅添加最后一个输入的输入,其余的被跳过。

for i in range(self.numInputsToAdd):
    self.additionalInputs["addnlInput" + str(i + 1)] = QLineEdit(self)
    self.additionalInputs["addnlInput" + str(i + 1)].setAlignment(Qt.AlignRight)
    self.additionalInputs["addnlInput" + str(i + 1)].setText("1")
    self.additionalInputs["addnlInput" + str(i + 1)].setPlaceholderText("Additional Mod Input #" + str(i + 1))
    self.vertCol.addWidget(self.additionalInputs["addnlInput" + str(i + 1)])

这是我当前正在生成要添加的输入的方式,self.numInputsToAdd是单击按钮后从弹出窗口中另一个qlineedit的值。上面的代码将输入放入名为self.additionalInputs的名为addnlInput1, addnlInput2..etc的字典中。

单击“滚动骰子”按钮后,它会触发一个函数,该函数将抓取AdditionalInputs字典的项并尝试将它们添加在一起,将它们分配给另一个变量,然后将该变量添加到{{1 }}

randint(1, n)

上面是“掷骰子”的相关代码

Here is a functional working example.当前,您需要在顶部的“修改器”输入框中输入内容。问题在于使用“更多修饰符?”生成的输入框。按钮。在那儿,它仅将底部修饰符输入添加到应用程序启动时位于顶部的修饰符输入框中。

我正在使用python 3.7.2和Windows 10。

1 个答案:

答案 0 :(得分:1)

我认为这个问题不是Qt特有的,而是循环的最后一行:

self.modDieResult = str(int(self.dieResult) + int(self.inputs['modInput'].text()) + int(self.newinputlist[keys]))

这里,您在循环的每次迭代中计算结果self.modDieResult。计算结果分配给self.modDieResult,这意味着最后将仅以最终的计算值结束。

要计算总和,您需要一个附加变量,例如

self.dieResult = str(randint(1, n))
self.newinputlist = {}

# Store the initial modInput value.
modInputResults = int(self.inputs['modInput'].text())

for k, v in self.additionalInputs.items():
    self.newinputlist[k] = self.additionalInputs[k].text()
    print(self.newinputlist[k])

    # On each loop, add the value for the additional elements.
    # Note you could do: int(v.text()) without the additional newinputlist.
    modInputResults = modInputResults + int(self.newinputlist[k])

self.modDieResult = self.dieResult + modInputResults

注意:由于变量仅包含单个键或值,因此我也将keysvalues更改为kv,不是多个。

相关问题