My intent is to provide a dialog where the user can enter and return a name value (or an empty string if the dialog is cancelled).
I have a custom dialog which has a QDialogButtonBox and a QLineEdit.The button box has OK and Cancel buttons. I would like to disable the OK button when the QLineEdit has an empty string.
This is my first posting, so please pardon me if there's an obvious solution
Here's part of my dialog:
class TableNameDialog(QDialog, Ui_TableNameDialog):
...
def exec(self):
execResult = super().exec()
if not execResult:
return ""
txt = self.tableNameLe.text()
if len(txt) > 0:
return txt
else:
return ""
And here's part of the dialog's UI in Qt Designer:
class Ui_TableNameDialog(object):
def setupUi(self, TableNameDialog):
...
self.tableNameLe = QLineEdit(TableNameDialog)
self.tableNameLe.setObjectName(u"tableNameLe")
self.formLayout.setWidget(0, QFormLayout.FieldRole, self.tableNameLe)
...
self.buttonBox = QDialogButtonBox(TableNameDialog)
self.buttonBox.setObjectName(u"buttonBox")
self.buttonBox.setEnabled(True)
self.buttonBox.setOrientation(Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
I'm darned if I know how to disable/enable the QDialogBox's OK button.
I've searched the QDialogButtonBox PySide6 docs but couldn't find anything pertinent.
Standard QDialogButtonBox buttons are accessible using the
button()function along with theirStandardButtonenum.You can therefore disable the Ok button depending on the contents of the line edit:
Notes:
str.strip()invalidate(), so that it will be considered acceptable as long as any non-space character has been entered;""anyway (return txt if len(txt) > 0 else ""is exactly the same asreturn txt);disconnectthetextEditedsignal before returning, otherwise it will be called as many times asexec()has been called on the same instance; alternatively use atry/exceptblock that attempts to connect the signal with theQt.UniqueConnectionargument, or just connect it within the__init__of the class;