简体   繁体   中英

how to connect slider to a function in PyQt4?

Im trying to translate a value of a slider to a function and display the value of this function in a lineEdit widget. Here is my code:

class MyForma1(object):
    def AddWidgets1(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(579, 542)
        self.horizontalSlider = QtGui.QSlider(Form)
        self.horizontalSlider.setGeometry(QtCore.QRect(120, 380, 321, 31))
        self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider.setInvertedAppearance(False)
        self.horizontalSlider.setInvertedControls(False)
        self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
        self.lineEdit = QtGui.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(112, 280, 331, 20))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(Form)
        QtCore.QObject.connect(self.horizontalSlider, QtCore.SIGNAL('valueChanged(int)'), Form.changeText)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))

class MyForma2(QtGui.QDialog, MyForma1):
    def __init__(self, z11=0):
        QtGui.QDialog.__init__(self)
        self.AddWidgets1(self)
        self.z = z11

    def myfunc1(self):
        self.z = self.horizontalSlider.value


    def changeText(self):
        self.myfunc1()
        self.lineEdit.setText(str(self.z))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Forma = MyForma2()
    Forma.show()
    sys.exit(app.exec_())

I want to retrieve the value of a slider and assign it to self.z and in this case i'd like to know what am i supposed to write instead of this: self.z = self.horizontalSlider.value

It should be self.horizontalSlider.value() , since value is a callable. However, the QHorizontalSlider.valueChanged signal also emits the value of the slider, so you can change your changeText method as follows:

def changeText(self, value):
    self.z = value
    self.lineEdit.setText(str(self.z))

Also consider using the new style signal-slot mechanisms: http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM