Reputation: 423
Using PyQt5, I'm trying to get a custom dialog (containing a simple QListWidget) to return a value. I know similar questions have been asked before but somehow I don't seem to get the answers to work.
The custom dialog is in this class:
class ListSelection(QDialog):
def __init__(self, item_ls, parent=None):
super(ListSelection, self).__init__(parent)
self.result = ""
#=================================================
# listbox
#=================================================
self.listWidget = QListWidget()
for item in item_ls:
w_item = QListWidgetItem(item)
self.listWidget.addItem(w_item)
self.listWidget.itemClicked.connect(self.OnSingleC lick)
self.listWidget.itemActivated.connect(self.OnDoubl eClick)
layout = QGridLayout()
row=0
layout.addWidget(self.listWidget,row,0,1,3) #col span=1, row span=3
#=================================================
# OK, Cancel
#=================================================
row +=1
self.but_ok = QPushButton("OK")
layout.addWidget(self.but_ok ,row,1)
self.but_ok.clicked.connect(self.OnOk)
self.but_cancel = QPushButton("Cancel")
layout.addWidget(self.but_cancel ,row,2)
self.but_cancel.clicked.connect(self.OnCancel)
#=================================================
#
#=================================================
self.setLayout(layout)
self.setGeometry(300, 200, 460, 350)
def OnSingleClick(self, item):
self.result = item.text()
def OnDoubleClick(self, item):
self.result = item.text()
self.close()
return self.result
def OnOk(self):
if self.result == "":
QMessageBox.information(self, "Error",
"One item must be selected")
return
self.close()
return self.result
def OnCancel(self):
self.close()
def GetValue(self):
return self.result
And this is what the calling function does:
def SomeFunction()
ls = ['apples','bananas','melons']
lb = ListSelection(ls)
if lb.exec_():
value = lb.GetValue()
print(value)
The problem is, this does not capture any value.
Thanks!
Upvotes: 1
Views: 9662
Reputation: 6065
The exec_
function does not return True
, so you never print the value.
According to the documentation, it return a QDialogCode
, an int. I tested with the code below, and it returns 0 (which evaluate to False
)
def SomeFunction():
ls = ['apples','bananas','melons']
lb = ListSelection(ls)
returnCode=lb.exec_()
print(returnCode)
value = lb.GetValue()
print(value)
So just don't put an if
, and it will print the value.
Edit:
I guess the correct behaviour would be to print the value if the user press Ok, and print nothing if the user press Cancel.
So instead of using QDialog.close()
, you can use QDialog.done(int)
, the integer being the QDialogCode
. This way you can keep your if
statement.
Upvotes: 3