0

I have a python plugin where the main.py file displays a QTextBrowser and writes some text. This works fine.

I wrote a second file anotherFile.py which identifies the same QTextBrowser but cannot write any text to it. Perhaps it needs to take ownership, I'm not sure?

Here is the code used:

# 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)
Joseph
  • 586
  • 1
  • 13
  • 32
  • I had a look at this post but it didn't help much: [https://stackoverflow.com/questions/45407616/calling-ui-objects-from-a-file-into-another](https://stackoverflow.com/questions/45407616/calling-ui-objects-from-a-file-into-another) – Joseph Nov 23 '17 at 12:08

2 Answers2

1

Your two classes both create their own ExampleDockWidget. Only one of them is shown (has its show method called) but there are two.

So it's not surprising that text sent to one does not appear on the other. You need to arrange for your anotherClass object to obtain a reference to the other ExampleDockWidget so it can share the same one.

strubbly
  • 3,347
  • 3
  • 24
  • 36
0

As strubbly mentioned, I need to reference the same ExampleDockWidget instead of creating separate versions. In the anotherFile.py file, I added an extra parameter to take in 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?'

And then inserted the reference in the main.py file:

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()
Joseph
  • 586
  • 1
  • 13
  • 32