Answer the question
In order to leave comments, you need to log in
How to bind objects in PyQt?
Hello!
I am developing a form using PyQt. I don't quite understand how the objects are connected to each other.
Example: I have a QLineEdit and a QCheckBox. When the status changes, the QCheckBox signals this and the QLineEdit becomes available or unavailable for input.
Right now I'm using the following structure:
self.MyChkbox.stateChanged.connect(
lambda state: self.MyLineEdit.setReadOnly(
True if state == 2 else False
)
)
Answer the question
In order to leave comments, you need to log in
class MyCheckBox(QCheckBox):
def __init__(self, target_edit:QLineEdit, parent):
super().__init__(parent)
self._target_edit = target_edit
self.stateChanged.connect(self._stateChanged_slot)
def _stateChanged_slot(self):
self._target_edit.setReadOnly(not self._target_edit.isReadOnly())
So far, we managed to solve it by assigning a custom attribute (property) in each checkbox. The attribute points to the name of the field that belongs to this checkbox.
When constructing the form, I set the attributes like this:
Then, when initializing the window, I do this:
for checkbox in self.findChildren(QCheckBox): # Для всех чекбоксов формы
if checkbox.property('field_name'): # Если чекбокс имеет свойство 'field_name'
checkbox.stateChanged.connect( # Законнектить смену статуса чекбокса к функции
# Функция поиска поля по имени объекта, содержащегося в свойстве отправителя (чекбокса)
lambda state : self.findChild(QLineEdit, self.sender().property('field_name')).setReadOnly(
True if state == 2 else False # Выставить соответствующий статус доступности для ввода
)
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question