applying python functions directly to Qt designer as signals

南楼画角 提交于 2019-12-02 21:07:24

The basic workflow when writing a PyQt4 gui is:

  1. Design the UI using Qt Designer.
  2. Generate a Python module from the UI file using pyuic4.
  3. Create an Application module for the main program logic.
  4. Import the GUI class into the Application module.
  5. Connect the GUI to the program logic.

So, given the UI file calc.ui, you could generate the UI module with:

pyuic4 -w calc.ui > calc_ui.py

And then create an application module something like this:

from PyQt4 import QtGui, QtCore
from calc_ui import CalculatorUI

class Calculator(CalculatorUI):
    def __init__(self):
        CalculatorUI.__init__(self)
        self.buttonCalc.clicked.connect(self.handleCalculate)

    def handleCalculate(self):
        x = int(self.lineEditX.text())
        y = int(self.lineEditY.text())
        self.lineEditZ.setText(str(x + y))

if __name__ == '__main__':

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

Note that it helps to set the objectName for every widget in Designer's Property Editor so that they can be easily identified later on. In particular, the objectName of the main form will become class-name of the GUI class that is imported (assuming the "-w" flag to pyuic4 is used).

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