我正在使用PySide构建一个应用程序,并希望能够从单独的.ui文件加载小部件。下面是我尝试过的一些代码,但它不会让我将从主窗口单独加载的Dock小部件停靠到主窗口。主窗口ui文件包含一个简单的主窗口和一些已停靠在其中的项目,dock_widget ui包含一个停靠小部件和里面的几个按钮。当我加载它时双击停靠小部件的栏,它似乎“停靠”到任何东西,当我将它拖到主窗口时它不会停靠。主窗口肯定接受停靠窗口小部件,因为它内部定义了一些行为正常。
#!/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>
关于我应该做些什么的任何想法
答案 0 :(得分:1)
你不应该致电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)