简体   繁体   中英

how to connect function to qt widget in qt designer? - python

I'm new in python and pyqt.

I create small app for big number multiply for exercise with console. now i'm try to run in into gui app. i create my app with function, my code is:

def digit(n):
        len(str(n))

def multi(u,v):
        n = max(digit(u),digit(v))

        if (u==0) or (v==0):
                return 0
        elif n < 4:
                return u*v
        else:
                m = int(n/2)

                x = u/10**m
                y = u%10**m

                w = v/10**m
                z = v%10**m

                return ( multi(x,w)*(10**m * 10**m) + (multi(x,z)+multi(w,y))*(10**m) + multi(y,z) )

i design a UI in qtDesigner some thing like this: 在此处输入图片说明

my question is how can i connect my function to the labels and calculate button? tnx

First, you need to save your form and convert it to a python module. You can do this using the pyuic tool:

    pyuic4 -o form_ui.py form.ui

Next, you need to create a script which will import the form_ui module and connect your application logic to the GUI. The base-class of the Window class must be the same as the top-level widget from Qt Designer (ie a QWidget , QMainWindow or QDialog ). And also note that the widgets from Qt Designer will become attributes of the ui object created in the __init__ method. Obvioulsy, you will need to change the names I've used in my example to match those from your actual ui.

from PyQt4 import QtCore, QtGui
from form_ui import Ui_Form

def digit(n):
    len(str(n))

def multi(u,v):
    n = max(digit(u),digit(v))

    if (u==0) or (v==0):
        return 0
    elif n < 4:
        return u*v
    else:
        m = int(n/2)

        x = u/10**m
        y = u%10**m

        w = v/10**m
        z = v%10**m

        return ( multi(x,w)*(10**m * 10**m) + (multi(x,z)+multi(w,y))*(10**m) + multi(y,z) )    

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.calcButton.clicked.connect(self.handleCalculate)

    def handleCalculate(self):
        u = int(str(self.ui.lineEdit1.text()))
        v = int(str(self.ui.lineEdit2.text()))
        # calculate answer...
        self.ui.label.setText(str(answer))

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

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