label displays sum of two QSpinBox (Python + Pyside)?

雨燕双飞 提交于 2019-12-23 05:09:38

问题


Could someone help me fix the code to display in the total column the sum of the two spinners 'Amount + Counter'. Currently the total label just displays the value of a single spinner. I need it to display the sum of both spinners. Any additional fixes or notes are welcome as I'm new to python.

Thank you very much.

BELOW IS THE FIXED WORKING CODE

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        #Add all GUI Elements to Class
        self.amountLabel = QtGui.QLabel('Amount')
        self.counterLabel = QtGui.QLabel('Counter')
        self.totalLabel = QtGui.QLabel('Total')
        self.amountSpin = QtGui.QSpinBox()
        self.counterSpin = QtGui.QSpinBox()

        self.totalOutput = QtGui.QLabel('0')

        grid = QtGui.QGridLayout()
        grid.setSpacing(0)

        grid.addWidget(self.amountLabel, 3, 0)
        grid.addWidget(self.counterLabel, 3, 1)
        grid.addWidget(self.totalLabel, 3, 2)

        grid.addWidget(self.amountSpin, 4, 0)
        grid.addWidget(self.counterSpin, 4, 1)
        grid.addWidget(self.totalOutput, 4, 2)

        self.setLayout(grid)

        # ACTIONS
        self.amountSpin.valueChanged[str].connect(self.onChanged)
        self.counterSpin.valueChanged[str].connect(self.onChanged)

        self.setGeometry(800, 400, 250, 80)
        self.setWindowTitle('Simple Calculator')
        self.show()

    def onChanged(self, val):
        #we ignore the val and just get the values directly from our spinboxes
        sum = self.amountSpin.value() + self.counterSpin.value()
        #and display them
        self.totalOutput.setText(str(sum))
        self.totalOutput.adjustSize()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

回答1:


Try this:

#Add all GUI Elements to Class
self.amountLabel = QtGui.QLabel('Amount')
self.counterLabel = QtGui.QLabel('Counter')
self.totalLabel = QtGui.QLabel('Total')
self.amountSpin = QtGui.QSpinBox()
self.counterSpin = QtGui.QSpinBox()

[...]

# ACTIONS
self.amountSpin.valueChanged[str].connect(self.onChanged)
self.counterSpin.valueChanged[str].connect(self.onChanged)

[...]

def onChanged(self, val):
    #we ignore the val and just get the values directly from our spinboxes
    sum = self.amountSpin.Value + self.counterSpin.Value
    #and display them
    self.totalOutput.setText(QString(sum))
    self.totalOutput.adjustSize()


来源:https://stackoverflow.com/questions/20898897/label-displays-sum-of-two-qspinbox-python-pyside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!