First, please let me explain the situation.
I have a QVBoxLayout
, which contains two QHBoxLayout
, one of them has a QLineEdit
and a QPushButton
, another has a single QLabel
, which should be filled with the text of QLineEdit
when button is pressed. That's it.
I know, how to handle buttonClicked
event, how to get the value of QEditText
and all that.
The main problem here is, how do I access the QLabel
and QLineEdit
instance inside the buttonClicked
event handler, specially when they are child of separate BoxLayout.
I have already solved this problem by defining them as class variables, so can access them from anywhere. But this is not a good design apparently. So, I am looking for a recommended way to solve this particular problem.
My Code:
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QLabel, QWidget, QPushButton, QLineEdit
class Example(QWidget):
def __init__(self):
super().__init__()
self.setUI()
def setUI(self):
h1box = QHBoxLayout()
line_edit = QLineEdit()
button = QPushButton("Submit")
button.clicked.connect(self.buttonClicked)
h1box.addWidget(line_edit)
h1box.addWidget(button)
h2box = QHBoxLayout()
label = QLabel("0")
h2box.addWidget(label)
vbox = QVBoxLayout()
vbox.addLayout(h1box)
vbox.addLayout(h2box)
self.setLayout(vbox)
self.show()
def buttonClicked(self):
# label needs to be filled with LineEdit value
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())