gpt4 book ai didi

python - 从 .ui 自动完成

转载 作者:行者123 更新时间:2023-12-04 11:01:31 26 4
gpt4 key购买 nike

我正在使用 Python3 和 PyQt5 开发一个应用程序,我的 UI 布局开始在 Qt .ui 文件中定义,并在运行时加载到我的 QDialog 类中。因此,当加载 UI 时,我的 UI 元素的实例(例如 QPushButton)会自动分配为我的 QDialog 类的实例变量。

问题在于,当我使用这些变量修改元素时,我没有得到任何类型的 Intellisense 类型提示或自动完成,因为 Python 和我的 IDE 不知道对象的类是什么。

在 Java 中,您可以使用显式缩小转换将您的对象转换为正确的类型,此时智能感知可以开始提供自动完成功能,因为它知道类型。

例如,在 Java 和 Android SDK 中:

TextView name = (TextView) findViewById(R.id.name); 

在此示例中,findViewById 返回一个 View,因此您可以使用类型转换来确保它被转换为 TextView。


在 Python 中,我想做同样的事情,既要确保我正在访问的 UI 元素是正确的类型,又要能够对实例方法使用自动完成。

这是我目前的情况:

""" 
Because Python doesn't know whether self.my_push_button is an instance
of QPushButton, this may or may not work, but it won't know until runtime,
so no autocompletion.
"""
self.my_push_button.setEnabled(False)

我想做的是这样的:

( (QPushButton) self.my_push_button ).setEnabled(False) 

我试过这个:

QPushButton(self.my_push_button).setEnabled(False)

但据我所知,它复制了原始对象并对新对象执行setEnabled,这显然不是我想要的。

我还尝试将 assert 语句与 isinstance 函数结合使用:

assert isinstance(self.my_push_button, QPushButton)

"""
This works for providing the code completion and checking the type.
However, it only works within the scope of the assert statement, so adding an assert for each variable in each scope in which it is used would be unnecessarily verbose.
"""
self.my_push_button.setEnabled(False)

我知道在 Python 中没有真正的对象“转换”,但是有什么方法可以在 Python 中实现类似于缩小转换的东西,如上所示,在 Java 中?

最佳答案

代码补全不像 uic 那样对动态生成的元素有效。

一种可能的解决方案是使用 pyuic 将 .ui 转换为 .py,然后使用 Using the Generated Code 中指示的类.

关于python - 从 .ui 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58770646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com