【问题标题】:Can't write to QTextBrowser when calling function from another file从另一个文件调用函数时无法写入 QTextBrowser
【发布时间】:2017-11-23 20:50:32
【问题描述】:

我有一个 python 插件,其中main.py 文件显示QTextBrowser 并写入一些文本。这工作正常。

我编写了第二个文件anotherFile.py,它标识了相同的 QTextBrowser,但不能向其中写入任何文本。也许它需要拥有所有权,我不确定?

这里是使用的代码:

# main.py #
from Example_dockwidget import ExampleDockWidget
from anotherFile import anotherClass

class Example:
    def __init__(self, iface):
        self.iface = iface

    def function(self):
        self.dockwidget = ExampleDockWidget()
        self.dockwidget.show()

        textBrowser = self.dockwidget.textBrowser
        #textBrowser.setText('This works!')
        a = anotherClass(self)
        a.anotherFunction()

# anotherFile.py #
from Example_dockwidget import ExampleDockWidget

class anotherClass:
    def __init__(self, iface):
        self.iface = iface
        self.dockwidget = ExampleDockWidget()

    def anotherFunction(self):
        textBrowser = self.dockwidget.textBrowser
        textBrowser.setText('This does not work!')
        print 'Why?'

# Example_dockwidget.py #
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'Example_dockwidget_base.ui'))

class ExampleDockWidget(QtGui.QDockWidget, FORM_CLASS):
    def __init__(self, parent=None):
        super(ExampleDockWidget, self).__init__(parent)
        self.setupUi(self)

【问题讨论】:

标签: python python-2.7 pyqt


【解决方案1】:

您的两个班级都创建了自己的ExampleDockWidget。只显示了其中一个(已调用其show 方法),但有两个。

因此,发送给一个人的文本不会出现在另一个人身上也就不足为奇了。您需要安排您的 anotherClass 对象以获取对另一个 ExampleDockWidget 的引用,以便它可以共享同一个。

【讨论】:

  • 谢谢,您的回答让我找到了解决方案:)
【解决方案2】:

正如strubbly 提到的,我需要引用相同的ExampleDockWidget 而不是创建单独的版本。在anotherFile.py 文件中,我添加了一个额外的参数来接收ExampleDockWidget

class anotherClass:
    def __init__(self, iface, dockwidget):
        self.iface = iface
        self.dockwidget = dockwidget

    def anotherFunction(self):      
        textBrowser = self.dockwidget.textBrowser
        textBrowser.setText('This does not work!')
        print 'Why?'

然后在main.py文件中插入引用:

def function(self):
    self.dockwidget = ExampleDockWidget()
    self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
    self.dockwidget.show()

    textBrowser = self.dockwidget.textBrowser
    #textBrowser.setText('This works!')
    a = anotherClass(self.iface, self.dockwidget)
    a.anotherFunction()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2022-12-20
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多