If you want to use test_list
, a variable created by a method of other_window
, from an instance of test
, you have a couple options.
Assuming you've defined an instance of test
globally somewhere, you can call need_list()
and give test_list
as an argument. For example:
class test(QtWidgets.QMainWindow):
def __init__(self, parent=None):
self.test.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect1)
def connect1(self):
window = other_window(self)
otherview.show()
def need_list(self, test_list):
print(test_list)
class other_window(QtWidgets.QMainWindow)
def __init__(self, parent=None):
self.other_window.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect2)
def connect2(self):
# do something
self.pushbutton.clicked.connect(self.return_list)
def return_list(self):
test_list = []
test_list.append("a", "b", "c")
return test_list
test_instance = test() # Or however you defined these
other_window_instance = other_window()
test_instance.need_list(other_window_instance.return_list())
You could also make test_list
global. This would require less change at the cost of some flexibility:
class test(QtWidgets.QMainWindow):
def __init__(self, parent=None):
self.test.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect1)
def connect1(self):
window = other_window(self)
otherview.show()
def need_list(self):
print(test_list)
class other_window(QtWidgets.QMainWindow)
def __init__(self, parent=None):
self.other_window.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect2)
def connect2(self):
# do something
self.pushbutton.clicked.connect(self.return_list)
def return_list(self):
global test_list
test_list = []
test_list.append("a", "b", "c")
test_instance = test()
other_window_instance = other_window()
Python has variable scopes (see the Python documentation on execution), meaning that in your original program, need_list()
is unable to see test_list
because it is defined locally. Anything outside that function is unable to see test_list
unless you declare it a global variable (with the global
keyword used in the second option, which allows it to be seen anywhere except in the bodies of functions that reassign to the same name. See this question for more about this) or pass it to a function explicitly (using a function argument in need_list()
as demonstrated in the first option).
Hope this helped!