Python PyQt - How to edit a variable in another function when function is run multiple times -
in pyqt5 program, have tabs , use 1 function creating same tab multiple times. in pyqt, run code when button clicked need connect function. in createatab function, have qlineedit needs edited when button clicked. here's example of trying do:
class example(qwidget, qwindow): def __init__(self): super().__init__() self.initui() def runthiswhenbuttonclicked(self): gettext = editthisline.text() editthisline.clear() # edits variable in other function except other function run multiple times def addthetab(self, username): addingtab = qwidget() abutton = qpushbutton("stuff") editthisline = qlineedit() abutton.clicked.connect(self.runthiswhenbuttonclicked) tabgrid = qgridlayout(addingtab) tabgrid.addwidget(editthisline, 3, 1, 4, 2) tabgrid.addwidget(abutton, 3, 3, 4, 3) tab_widget.addtab(addingtab, str(username)) def initui(self): global tab_widget tab_widget = qtabwidget() listwidget = qlistwidget() listwidget.itemdoubleclicked.connect(self.addthetab) splitterrr = qsplitter() splitterrr.addwidget(listwidget) splitterrr.addwidget(tab_widget) qlistwidgetitem("test1", listwidget) qlistwidgetitem("test2", listwidget) mainlayout = qhboxlayout() mainlayout.addwidget(splitterrr) self.setlayout(mainlayout) self.setgeometry(300, 300, 300, 300) self.setwindowtitle('test') self.show() if __name__ == '__main__': app = qapplication(sys.argv) ex = example() sys.exit(app.exec_())
i have read through , although explain lot, doesn't explain how solve issue.
this explains how passing function, not calling it. so, passing variables runthiswhenbuttonclicked function not possible.
the concept missing closure. closure wraps scope function, code in function can access variables within associated scope. simplest way utilise closures when connecting signals lambda
(although people prefer use functools.partial).
in example, mean connecting signal this:
abutton.clicked.connect(lambda: self.runthiswhenbuttonclicked(editthisline)) ... def runthiswhenbuttonclicked(self, editthisline): print(editthisline.text())
however, think may "papering on cracks" in code, , possibly not best solution. better solution make proper use of namespaces classes provide. addthetab
, runthiswhenbuttonclicked
should refactored tab
class has child widgets attributes:
class tab(qwidget): def __init__(self, parent=none): super(tab, self).__init__(parent) self.editthisline = qlineedit() self.abutton = qpushbutton("stuff") self.abutton.clicked.connect(self.runthiswhenbuttonclicked) ... def runthiswhenbuttonclicked(self): print(self.editthisline.text())
this eliminate need closures in example.
Comments
Post a Comment