本文介绍了将 python 函数作为信号直接应用到 Qt 设计器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Qt 和 GUI 编程的新手,但我已经在 python 中进行了大量编码 - 编写模块等.我需要为我的一些旧模块开发简单的 GUI.

I am new to Qt and GUI programming overall but i have done a fair bit of coding in python - writing modules and so on. I need to develop simple GUIs for some of my old modules.

我正在尝试做的事情可以用以下简单示例表示:

What i am trying to do can be represented by the following simple example:

def f(x, y):
    z = x + y
    return z

对于这个函数,我将为 x 和 y 提供两行编辑,对 z 进行一次编辑.现在我创建一个按钮计算",当我这样做时,我希望它从行编辑中获取 x 和 y 运行函数 f(x,y) 并将输出提供给 z.

For this function i will give two line-edits for x and y and one for z. Now i create a push-button 'calculate' and when i do that i want it to take x and y from the line-edits run the function f(x,y) and give the output to z.

有没有办法直接在Qt Designer中添加python编写的函数f(x,y)?

Is there any way to do this directly in Qt Designer by adding the function f(x,y) written in python?

如果不是,还有什么选择?

If not what are the alternatives?

推荐答案

编写 PyQt4 gui 的基本工作流程是:

The basic workflow when writing a PyQt4 gui is:

  1. 使用 Qt Designer 设计 UI.
  2. 使用 pyuic4 从 UI 文件生成 Python 模块.
  3. 为主程序逻辑创建一个应用程序模块.
  4. 将 GUI 类导入应用程序模块.
  5. 将 GUI 连接到程序逻辑.
  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.

因此,给定 UI 文件 calc.ui,您可以使用以下命令生成 UI 模块:

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_())

请注意,在 Designer 的属性编辑器中为每个小部件设置 objectName 会有所帮助,以便以后可以轻松识别它们.特别是,主窗体的 objectName 将成为导入的 GUI 类的类名(假设使用了 pyuic4 的-w"标志).

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).

这篇关于将 python 函数作为信号直接应用到 Qt 设计器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 06:57