Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling editing QLineEdit

I would like to make it so under certain conditions, it is impossible to edit a QLineEdit widget. Ideally, it would look something like:

QLE_On = QCheckBox("Non-editable?")
generic = QLineEdit()

if QLE_On.isChecked():
#disable editing of generic

Looking at the docs, .isReadOnly might be one possible option how to achieve what I'm looking for, but I'm not quite sure how to implement that.

like image 682
Not-my-dearly Avatar asked Jun 11 '26 01:06

Not-my-dearly


2 Answers

Simply make the lineEdit uneditable by making it False:

self.lineEdit.setEnabled(False)
like image 54
Vinamra Jaiswal Avatar answered Jun 12 '26 14:06

Vinamra Jaiswal


To be able to establish that the QLineEdit is editable or you should not use the setReadOnly() function.

You can know the state of the checkbox synchronously and asynchronously through the checkState() function and the stateChanged signal. In your case you need both, the first to set the initial value and the second when you do a check through the GUI, in your case the following code is the solution:

generic.setReadOnly(QLE_On.checkState()!=Qt.Unchecked)
QLE_On.stateChanged.connect(lambda state: generic.setReadOnly(state!=Qt.Unchecked))

Example:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


app = QApplication(sys.argv)
w=QWidget()
w.setLayout(QVBoxLayout())

QLE_On = QCheckBox("Non-editable?")
generic = QLineEdit()

generic.setReadOnly(QLE_On.checkState()!=Qt.Unchecked)
QLE_On.stateChanged.connect(lambda state: generic.setReadOnly(state!=Qt.Unchecked))

w.layout().addWidget(QLE_On)
w.layout().addWidget(generic)
w.show()
sys.exit(app.exec_())
like image 43
eyllanesc Avatar answered Jun 12 '26 16:06

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!