我正在尝试获取窗口的所有按钮子窗口小部件。按钮是通过 QDialogButtonBox 创建的。如何获取哪一个是取消/确定/保存按钮?
我有:
QWidget *pWin = QApplication::activeWindow();
QList<QPushButton *> allPButtons = pWin->findChildren<QPushButton *>();
QListIterator<QPushButton*> i(allPButtons);
while( i.hasNext() )
{
//identify which button is cancel/ok/save button here
/*Note: This is where I'm having trouble, getting the text of the
button here returns NULL. Any other way of Identifying which is
which?
Is it a special case when buttons are created through QDialogButtonBox?
*/
}
答案 0 :(得分:3)
您应该使用QDialogButtonBox::button()方法获取相应role的按钮。
例如:
QPushButton* pOkButton = pButtonBox->button(QDialogButtonBox::Ok);
QPushButton* pCancelButton = pButtonBox->button(QDialogButtonBox::Cancel);
// and so on...
一般来说,我会说从文本中找到一个按钮是个坏主意,因为当你的应用程序国际化时,这个文本可能会改变。
答案 1 :(得分:0)
一种方法是来自构造函数的text
参数,例如QPushButton(const QString & text, QWidget * parent = 0)
:
QPushButton* buttonSave = new QPushButton("Save");
// etc..
while( i.hasNext() )
{
//identify which button is cancel/ok/save button here
if(i.next()->text() == "Save") {
// do something to save push button
}
}