收集所有停靠的小部件及其位置
Posted
技术标签:
【中文标题】收集所有停靠的小部件及其位置【英文标题】:Collect all docked widgets and their locations 【发布时间】:2017-11-09 16:15:10 【问题描述】: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_())
【问题讨论】:
【参考方案1】:没有获取停靠小部件列表的便捷方法。但是,无论何时添加停靠小部件,它都会自动重新设置为主窗口的父级,因此您可以改用主窗口的 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)'
【讨论】:
以上是关于收集所有停靠的小部件及其位置的主要内容,如果未能解决你的问题,请参考以下文章