PySide 中有没有办法收集所有停靠的小部件,以及它们是停靠在主窗口的左侧还是右侧?
如果我的第一个问题没有答案,我如何至少找出小部件是停靠在左侧还是右侧?
from PySide import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.textEdit = QtGui.QTextEdit()
self.setCentralWidget(self.textEdit)
self.createActions()
self.createMenus()
self.createToolBars()
self.createStatusBar()
self.createDockWindows()
self.setWindowTitle("Dock Widgets")
def createActions(self):
self.toggleLeftAct = QtGui.QAction(
"&Toggle Left", self, shortcut=QtGui.QKeySequence("Ctrl+L"),
statusTip="Toggle Left Sidebar",
triggered=self.toggleLeft)
self.toggleRightAct = QtGui.QAction(
"&Toggle Right", self, shortcut=QtGui.QKeySequence("Ctrl+R"),
statusTip="Toggle Right Sidebar",
triggered=self.toggleRight)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu("&File")
self.fileMenu.addAction(self.toggleLeftAct)
self.fileMenu.addAction(self.toggleRightAct)
self.viewMenu = self.menuBar().addMenu("&View")
def createToolBars(self):
self.fileToolBar = self.addToolBar("File")
self.fileToolBar.addAction(self.toggleLeftAct)
self.fileToolBar.addAction(self.toggleRightAct)
def createStatusBar(self):
self.statusBar().showMessage("Ready")
def createDockWindows(self):
self.dockCustomers = QtGui.QDockWidget("Customers", self)
self.dockCustomers.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
self.customerList = QtGui.QListWidget(self.dockCustomers)
self.dockCustomers.setWidget(self.customerList)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dockCustomers)
self.viewMenu.addAction(self.dockCustomers.toggleViewAction())
self.dockParagraphs = QtGui.QDockWidget("Paragraphs", self)
self.paragraphsList = QtGui.QListWidget(self.dockParagraphs)
self.dockParagraphs.setWidget(self.paragraphsList)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dockParagraphs)
self.viewMenu.addAction(self.dockParagraphs.toggleViewAction())
def toggleLeft(self):
print self.dockCustomers
print self.dockParagraphs
def toggleRight(self):
print 'toggle Right'
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
没有方便的方法可以获取停靠小部件的列表。但是,每当添加停靠小部件时,它都会自动重铸到主窗口,因此您可以使用主窗口的 findChildren 方法:
for dock in self.findChildren(QtGui.QDockWidget):
print(dock.windowTitle())
dock-widget 当前所在的区域可以通过主窗口的 dockWidgetArea 方法找到:
area = self.dockWidgetArea(dock)
if area == QtCore.Qt.LeftDockWidgetArea:
print dock.windowTitle(), '(Left)'
elif area == QtCore.Qt.RightDockWidgetArea:
print dock.windowTitle(), '(Right)'