如何获取QDialogBu​​ttonBox创建的按钮的名称?

时间:2010-12-01 02:50:31

标签: c++ qt button widget

我正在尝试获取窗口的所有按钮子窗口小部件。按钮是通过 QDialogBu​​ttonBox 创建的。如何获取哪一个是取消/确定/保存按钮?

我有:

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?       
   */
}

2 个答案:

答案 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
  }
}