PySide PyQt MainWindow 或来自深度嵌套小部件的中央小部件访问 [英] PySide PyQt MainWindow or Central Widget access from deeply nested widgets

查看:47
本文介绍了PySide PyQt MainWindow 或来自深度嵌套小部件的中央小部件访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向 PyQt 专家寻求一些最佳实践.

Calling out to PyQt gurus for some best practices.

我有一些应用程序通用属性,我将它们定义为 QApplication 上的属性.在我的 MainWindow 初始化中,我为 MainWindow 分配了一个app"属性.我想在深度嵌套的小部件中访问应用程序的变量.现在,我可以通过调用足够多的parent()"调用来达到 MainWindow 的级别.

I have some application universal attributes that I define as attributes on my QApplication. In my MainWindow initialization I assign an "app" attribute to the MainWindow. I would like to access the app's variables in deeply nested widgets. Right now, I can do so by calling enough "parent()" calls to get up to the level of MainWindow.

这看起来很笨拙,我猜还有另一种解决方案是这种情况下的最佳实践.以下是一些代码片段,可帮助您更好地理解问题.

This seems kludgey and my guess is there is another solution that is best practice in this situation. Here are some snippets of code to better understand the issue.

应用类

class App(QtGui.QApplication):

    def __init__(self, sim, *args, **kwargs):
        super(App, self).__init__(*args, **kwargs)
        self.sim = sim
        window = MW.BaseUI(digi_thread, app=self)

主窗口类

class BaseUI(QtGui.QMainWindow):
    def __init__(self, digi_thread, app, parent=None):
        super(BaseUI, self).__init__(parent)
        self.app = app

从嵌套小部件(标签簿中的标签)进入主窗口的一些代码示例

An example of some code to get up to Main Window from a nested widget (a tab within a tabbook)

@property
def main_window(self):
    return self.parent().parent().parent().parent()

def some_function(self):
    if self.main_window.app.sim:
        print "in simulation mode"

我也不确定 centralWidget 是否与解决此类问题有关.

I'm also not sure if the centralWidget has anything to do with solving this type of issue.

推荐答案

您始终可以通过 PySide.QtCore.QCoreApplication.instance() 访问当前应用程序实例.在 C++ 中,全局 qApp 变量提供相同的功能.

You can always get to the current application instance via PySide.QtCore.QCoreApplication.instance(). In C++, the global qApp variable provides the same functionality.

因此,无论您在全局应用程序实例上设置 python 属性还是 Qt 属性,您都可以随时访问它,而无需经过任何层次结构.

So, whether you set python attributes, or Qt properties, on the global application instance, you can always get to it without having to go through any hierarchies.

这篇关于PySide PyQt MainWindow 或来自深度嵌套小部件的中央小部件访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆