开发者

Use QMessageBox to choose from a list of options

I'm newly moving from Java to Qt, and I have a question. In JOptionPane you can pass an array of choices and JOpti开发者_如何转开发onPane will automatically make a combo box for the user to select a choice from. Is something analogous to this possible in Qt with QMessageBox or another native Qt element?


You should use QInputDialog::getItem(). For example:

QStringList fruits;
fruits << "Apple" << "Banana" ... ;
QString fruit = QInputDialog::getItem(this, "Select fruit", "Fruit:", fruits);


You could just read QMessageBox reference.

I am copy-pasting code sample from it:

QMessageBox msgBox;
 msgBox.setText("The document has been modified.");
 msgBox.setInformativeText("Do you want to save your changes?");
 msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
 msgBox.setDefaultButton(QMessageBox::Save);
 int ret = msgBox.exec();
 switch (ret) {
   case QMessageBox::Save:
       // Save was clicked
       break;
   case QMessageBox::Discard:
       // Don't Save was clicked
       break;
   case QMessageBox::Cancel:
       // Cancel was clicked
       break;
   default:
       // should never be reached
       break;
 }

This code creates a message box with three buttons (Save, Discard, Cancel). Save button is focused.

You can combine values from Standard buttons using bitwise OR operator in setStandardButtons function.

If you need some options known only at runtime I can propose this possible solution.

QMessageBox msgBox;

//set common message box parameters. (informative text, etc)

//iterate through possible options. For each possible option:
{
  QPushButton *button = msgBox.addButton(myQStringOption, QMessageBox::AcceptRole);
  connect(button, SIGNAL(clicked()), /* response object */, SLOT(/*response slot*/));
}

msgBox.exec();

I am not sure this is the most elegant solution but it should works.

If you don't want to use signals and slots you could use clickedButton() method to determine which button was pressed.

msgBox.exec();

if ((msgBox.clickedButton())->text() == myQStringOption){
  //doStuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜