How to get the role of a QPushButton created by a QDialogButtonBox?
I'm trying get all the button child widgets of a currently active window. The buttons were created开发者_开发技巧 through QDialogButtonBox. I'm trying to get the roles of each button so I can identify which button is the OK, CANCEL, or SAVE button. However I'm getting an error with the following code:
QWidget *pWin = QApplication::activeWindow();
QList<QPushButton *> allPButtons = pWin->findChildren<QPushButton *>();
QListIterator<QPushButton*> i(allPButtons);
while( i.hasNext() )
{
QDialogButtonBox *pButtonRole = new QDialogButtonBox();
QDialogButtonBox::ButtonRole role = pButtonRole->buttonRole(i.next());
qDebug() << "buttonRole: " << role << endl ;
//the value of role here is -1, which means it's an invalid role...
}
I'm getting a negative value when getting the button's role :(
Can somebody tell me what's wrong with the code?
You can't call a non-static method like that. You need to have the QDialogButtonBox
variable and call that particular instance for buttonRole()
to work.
QDialogButtonBox::ButtonRole role = myButtonBoxPtr->buttonRole(i.next());
You are creating a new empty QDialogButtonBox
which has no idea about buttons
in allPButtons
list. Calling buttonRole()
on them returns -1 (InvalidRole) because buttons
are not in that button-box
.
You must do as jkerian wrote and myButtonBoxPtr
must point to the QDialogButtonBox
which is already in your window.
You can try something like this (if you have one ButtonBox):
QDialogButtonBox *box = pWin->findChild<QDialogButtonBox *>();
foreach(QAbstractButton* button, box->buttons())
{ qDebug() << box->buttonRole(button); }
精彩评论