如何使用 PyQt4.uic.loadUi 将第二个 .ui 加载到 self 中? [英] How to load second .ui into self with PyQt4.uic.loadUi?
问题描述
我正在创建一个加载几个 .ui 文件的应用程序.第一个是 QMainWindow 类型,其他是 QWidget 类型.
我不知道如何将第二个 UI (module.ui
) 加载到 self 中,从而通过 self.
访问小部件.>
如何实现?
from PyQt4 import QtGui从 PyQt4 导入 uic类 TestApp(QtGui.QMainWindow):def __init__(self):super(TestApp, self).__init__()# 加载主窗口和模块uic.loadUi('main_window.ui', self) # QMainWindow,包含testLayout,加载到selfui_module = uic.loadUi('module.ui') # QWidget# 将模块附加到主窗口self.testLayout.addWidget(ui_module) # 这很好用# 在 UI 模块中编辑小部件self.label.setText('Hello') # 不起作用(因为 self.label 不存在)
我可以这样做:
self.label = ui_module.labelself.label.setText('你好')
...但我想从一开始就将 UI 加载到 self 中.
如果我尝试将 UI 加载到 self 中,则会出现错误:
uic.loadUi('module.ui', self)>>>QLayout: 试图将 QLayout "" 添加到已经有布局的 TestApp "Form"
您需要创建一个小部件来加载 ui 文件
self.widget = QWidget(self)uic.loadUi('module.ui', self.widget)self.widget.label.setText('你好')
话虽如此,如果您为其他小部件创建一个单独的类可能会更好.
class MyWidget(QWidget):def __init__(self, **args, **kwargs):super(MyWidget, self).__init__(*args, **kwargs)uic.loadUi('module.ui', self)self.label.setText('你好')类 TestApp(QtGui.QMainWindow):def __init__(self):...self.widget = MyWidget(self)
I'm creating an application which loads a couple of .ui files. The first one is of type QMainWindow and the others are of type QWidget.
I can't figure out how to load the second UI (module.ui
) into self, making widgets accessible through self.<widget_name>
.
How can this be achieved?
from PyQt4 import QtGui
from PyQt4 import uic
class TestApp(QtGui.QMainWindow):
def __init__(self):
super(TestApp, self).__init__()
# Load main window and the module
uic.loadUi('main_window.ui', self) # QMainWindow, contains testLayout, loads into self
ui_module = uic.loadUi('module.ui') # QWidget
# Attach module to main window
self.testLayout.addWidget(ui_module) # this works fine
# Edit widget in UI module
self.label.setText('Hello') # does not work (since self.label doesn't exist)
I could do this:
self.label = ui_module.label
self.label.setText('Hello')
...but I'd like to instead load the UI into self from the start.
If I try to load the UI into self, I get an error:
uic.loadUi('module.ui', self)
>>> QLayout: Attempting to add QLayout "" to TestApp "Form", which already has a layout
You need to create a widget to load the ui file onto
self.widget = QWidget(self)
uic.loadUi('module.ui', self.widget)
self.widget.label.setText('Hello')
That being said, it would probably be better if you created a separate class for the other widget.
class MyWidget(QWidget):
def __init__(self, **args, **kwargs):
super(MyWidget, self).__init__(*args, **kwargs)
uic.loadUi('module.ui', self)
self.label.setText('Hello')
class TestApp(QtGui.QMainWindow):
def __init__(self):
...
self.widget = MyWidget(self)
这篇关于如何使用 PyQt4.uic.loadUi 将第二个 .ui 加载到 self 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!