我的 pyqt 遇到以下问题:
假设我在 Qt Designer 中创建一个对象并将其保存为 .ui 文件。然后我使用 pyuic 将其转换为 .py 文件。因为我想将新模块集成到给定程序中,所以这是最喜欢的方法(因为稍后 .ui 文件将在启动时自动转换为 .py 文件)。
如果我查看我的 .py 文件,我会在窗口中看到以下内容:
class Ui_SubWindow(object):
def setupUi(self, SubWindow):
SubWindow.setObjectName(_fromUtf8("SubWindow"))
....
我有一个
RemoteWindow
类作为 MainWindow,其中启动 SubWindow
:
class RemoteWindow(QtGui.QMainWindow):
def __init__(self, subcore):
super(RemoteWindow, self).__init__(subcore.core.gui)
self.subcore = subcore
self.ui = Ui_SubWindow()
现在我有了一个核心程序:
class SubCore(object):
def __init__(self, core, identity, number):
...
self.gui = RemoteWindow(self)
self.newController = NewController(self.gui)
和新的控制器类:
class NewController(object):
def __init__(self, subwindow):
self.subwindow = subwindow
self.ui = subwindow.ui
从我的控制器我想在该窗口上调用 .findChild()
submitFrame = self.ui.findChild(QtGui.QFrame, "frameSubmit")
,但我得到的只是:
AttributeError: 'Ui_SubWindow' object has no attribute 'findChild'
我认为这是因为类
Ui_SubWindow
不是某个 QObject 的子类,而是一个对象的子类,对吗?
self.ui
与 subwindow.ui
相同,其中 subwindow
是 RemoteWindow
的实例,其 .ui
参数为 Ui_SubWindow
类。
是否有机会让 pyuic 或 Qt Designer 使该子窗口成为 QObject 的子窗口,无需操作自动生成的 .py 文件?
您根本不需要使用
findChild
,因为 pyuic 会自动在 ui
对象中为 Qt Designer 中定义的所有小部件创建属性。属性名称取自 objectName
。所以你需要的是:
submitFrame = self.ui.frameSubmit
Qt Designer 创建一个设计,即一个用于填充主小部件的类,因此内部小部件不是此类的子级,如果您想使用 findChild,则必须对调用后返回此类的小部件执行此操作方法setupUi。
class RemoteWindow(QtGui.QMainWindow):
def __init__(self, subcore):
super(RemoteWindow, self).__init__(subcore.core.gui)
self.subcore = subcore
self.ui = Ui_SubWindow()
self.ui.setupUi(self) # Here the widget is filled
[...]
然后你应该按以下方式使用它:
class NewController(object):
def __init__(self, subwindow):
self.subwindow = subwindow
submitFrame = self.subwindow.findChild(QtGui.QFrame, "frameSubmit")
[...]
我最近不得不做同样的事情,并将其留在这里,以防有人看到此链接与其他相关链接。 https://stackoverflow.com/a/62340205/1621381
for name, obj in dict(self.__dict__).items():
# print(str(name) + str(obj))
obj_type = str(obj).strip("<PyQt5").rsplit(" ")[0].replace(".", '', 1)
# obj_type = str(obj).strip("<").rsplit(" ")[0]
# print(obj_type)
# obj_type = obj_str.strip("<PyQt5").rsplit(" ")[0].replace(".", '', 1)
label_name = "self." + str(name)
try:
label_name = self.findChild(eval(obj_type), name)
print(str(label_name) + ' created')
except:
pass
if not isinstance(obj_type, QObject):
continue