python - 从 .ui 自动完成

标签 python python-3.x pyqt pyqt5 qt-designer

我正在使用 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/

相关文章:

python -\b 字符的反义词是什么,即一种不可删除的空格?

python - 使用 Python strptime 解析月份名称时出现 UnicodeEncodeError

python-3.x - 向重写的函数添加额外的参数,而不会出现 pylint 提示

python - 线程和委托(delegate) - 类的多线程

python - python函数是否有可能返回超过1个值?

python - 使用 multiprocessing.dummy 并行请求

python-3.x - QStatusBar.showMessage() 没有持续更新

python - 通过导入 PyQt5 Ui 为按钮添加功能

python - PyQt5 GUI - 使用 PyInstaller 制作的 exe 无法打开

python - Python 3 的 UTF-8 编码问题