我使用使用Qt
编写的软件,并且它具有QMainWindow
对象。添加到QMainWindow
对象已经存在时,我需要获取小部件的引用。我看过Qt文档。我希望有一个事件childAdded
或其他什么,但我找不到任何东西。
请查看此代码:
import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QDockWidget
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.button = QPushButton("A Button!")
self.setCentralWidget(self.button)
def do_something(w):
w.setWindowTitle("Newly Added")
def add_dock_widget(win):
win.addDockWidget(Qt.RightDockWidgetArea, QDockWidget())
app = QApplication(sys.argv)
window = MainWindow()
window.show()
add_dock_widget(window)
# At this point, somehow, I need to get the reference of added widget.
# Because add_dock_widget method doesn't return any reference.
# I'm looking for something like that, so that I can manipulate the widget:
# window.childAdded[****].connect(do_something)
app.exec_()
该软件允许在其中编写python脚本。将子级添加到GUI后,我需要使用脚本更改子级内的某些内容。
您可以简单地从add_dock_widget
返回停靠小部件,如下所示:
def add_dock_widget(win):
dock = QDockWidget(win)
win.addDockWidget(Qt.RightDockWidgetArea, dock)
return dock
app = QApplication(sys.argv)
window = MainWindow()
window.show()
dock = add_dock_widget(window)
do_something(dock)
根据您的背景目标,有几种选择:
如果知道对象类,则可以使用findChild或findChildren:
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
add_dock_widget(window)
dockwidget = window.findChild(QDockWidget)
do_something(dockwidget)
# or
# for dockwidget in window.findChildren(QDockWidget)
# do_something(dockwidget)
app.exec_()
但是此方法受到限制,因为您可以有许多相同类型的小部件,并且您无法区分哪个对象是您想要的对象,因此您必须做一些传递给另一个功能的新过滤器。
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.button = QPushButton("A Button!")
self.setCentralWidget(self.button)
def event(self, e):
if e.type() == QEvent.ChildAdded:
if isinstance(e.child(), QDockWidget):
do_something(e.child())
return super(MainWindow, self).event(e)