我正在使用PySide构建一个应用程序,并希望能够从单独的.ui文件加载小部件。下面是我尝试过的一些代码,但它不能让我停靠从主窗口单独加载到主窗口的码头小部件。主窗口ui文件包含一个简单的主窗口和一些已经停靠在其中的项目,dock_widget ui包含一个停靠小部件和一些按钮。当我双击dock小部件的栏,一旦它加载,它似乎"停靠"到什么,当我把它拖到主窗口,它不会停靠。主窗口肯定接受dock小部件,因为其中定义了一些正常运行的部件。
#!/usr/bin/python
# Import PySide classes
import sys
from PySide.QtGui import *
from PySide.QtCore import *
from PySide.QtUiTools import QUiLoader
def load_ui(ui_file, parent=None):
loader = QUiLoader()
file = QFile(ui_file)
file.open(QFile.ReadOnly)
myWidget = loader.load(file, None)
myWidget.show()
file.close()
myWidget.show()
return myWidget
# Create a Qt application
app = QApplication(sys.argv)
# Create a Label and show it
main_window = load_ui("ui/main_window.ui")
dock_widget = load_ui("ui/console.ui", main_window)
# Enter Qt application main loop
app.exec_()
sys.exit()
console.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DockWidget</class>
<widget class="QDockWidget" name="DockWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>542</width>
<height>261</height>
</rect>
</property>
<property name="contextMenuPolicy">
<enum>Qt::DefaultContextMenu</enum>
</property>
<property name="windowTitle">
<string>DockWidget</string>
</property>
<widget class="QWidget" name="dockWidgetContents">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextEdit" name="textEdit_2"/>
</item>
<item>
<widget class="QTextEdit" name="textEdit"/>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
我该怎么做呢
不应该调用QDockWidget::show
。这迫使它像普通的QWidget一样工作。使用QMainWindow::addDockWidget
代替。
def load_ui(ui_file, parent=None):
loader = QUiLoader()
file = QFile(ui_file)
file.open(QFile.ReadOnly)
myWidget = loader.load(file, None)
file.close()
return myWidget
main_window = load_ui("ui/main_window.ui")
dock_widget = load_ui("ui/console.ui", main_window)
main_window.show()
main_window.addDockWidget(Qt.LeftDockWidgetArea, dock_widget)