Custom Button Dialog - Is there a better way?
Stretch65
Posts: 166
Hi,
I was wanting to display a message box that give's the user 4 choices. The standard DzMessageBox has methods that allow up to 3 buttons/choices for the user, so I thought I would design a custom dialog that allows a variable number of buttons to be displayed. The snippet shows how I've gone about this, and in particular how I've connected each button's signal with a function that tells me which button has been pressed. The code seems to work OK, but I'm no javascript guru. I can't help wondering if there's a better way of coding this instead of using 'eval()':
var oDlg = new DzDialog();oDlg.caption = "My Dialog Box";var nBtnPressed;var oVBoxLayout = new DzVBoxLayout(oDlg);oVBoxLayout.autoAdd = true; for (var i = 0; i < 4; i++) { var oBtn = new DzPushButton(oDlg); oBtn.autoDefault = false; oBtn.text = "Button: " + i; var code = "function fnc() {" + " nBtnPressed = " + i + ";" + " oDlg.close();" + "}"; eval(code); connect(oBtn, "clicked()", fnc ); }oDlg.exec();print(nBtnPressed);
Comments
Your script is quite good. I cannot say a better way, but another way without using the eval(), could be:
I just added another property .btnIndex = i at each button in line 13 and I change the connect syntax into: object.singal.connect(thisItem, function);
I also put the fnc function out of the loop so the same code is called for each button. The "this" item is the one you have sent through the connection (thisItem).
As I said, it is not better than yours .... it is just another way .... :-)
Note that signals and slots are one of the areas that will be changing a lot in DS5 - the documents have been updated.
Thanks Mike. That code definitely looks better. Thank you very much for this.
Tried to pack the code into a function to improve reusability. The adjustments are a bit dirty as I don't know how to get a parent widget and had to work around that but it works well enough for me.