PyQT or Programming Structure Question

Hello guys, I have been trying to declare a variable globally (var below) when I click in an item of a list (calling fn1), so I can have it identified when I click in another list (calling fn2).

I tried to pass the argument but it doesnt work for me as the event “clicked” asks some sytax that I dont know how to do it, or I am making some mistake.

Anyone has a possible solution for that?

Thanks in advance!

class HairTubeTool(QtWidgets.QWidget):
    Create a default tool window.
    global var
    def __init__(self, parent = None):
        Initialize class
        super(HairTubeTool, self).__init__(parent = parent)
        self.widgetPath = ("")
        self.widget = QtUiTools.QUiLoader().load(self.widgetPath)
        # initial window size
        self.resize(400, 720)
        # >>>>> LISTS
        # a_list
        self.a_list = self.widget.findChild(QtWidgets.QListView, 'a_list')
        self.list1 = QtGui.QStandardItemModel()
        # b_list
        self.b_list = self.widget.findChild(QtWidgets.QListView, 'b_list')
        self.list2 = QtGui.QStandardItemModel()

    def fn1(self, index):
        var = self.list1.itemFromIndex(index)
    def fn2(self, index):
        print (var)

Global variables are generally a bad idea.

What you probably want to do here is set a member variable on your class in your __init__ method, and then use that member variable in your fn1 and fn2

So you’d do something like this:

    def __init__(self, parent=None):
        self.var = None

    def fn1(self, index):
        self.var = self.list1.itemFromIndex(index)
    def fn2(self, index):
1 Like

global var just tells python to search for var at the top level of the module, which you do not have declared in your example so I would be surprised it doesn’t cause an error.

But otherwise as @tfox_TD said set it as an instance variable that way it can be accessed by all the methods via self. This is the intended design of classes, that they contain their own data and ideally do not modify anything external to themselves.

1 Like

thank you so much @tfox_TD and @Munkybutt !
now I got how it works!


1 Like