Have a combobox inside a message box

大憨熊 提交于 2019-12-12 22:27:24

问题


I want to create a combobox inside a message box and return the selected value to be used later.

I can do the same on the window itself but not sure how to do that inside a combobox.

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->comboBox->addItem("Red");
    ui->comboBox->addItem("Blue");
    ui->comboBox->addItem("Green");
    ui->comboBox->addItem("Yellow");
    ui->comboBox->addItem("Pink");
    ui->comboBox->addItem("Purple");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
       QMessageBox::about(this,"Choose color of rectangle", ui->comboBox->currentText() );
}

回答1:


If I understand you correct you would like to show a combobox in a separate dialog window for the user to select some option.

One of the ways to do that, would be to subclass QDialog. If a combo field and a button to accept is sufficient the class could look as below:

class CustomDialog : public QDialog
{
public:
    CustomDialog(const QStringList& items)
    {
        setLayout(new QHBoxLayout());

        box = new QComboBox;
        box->addItems(items);
        layout()->addWidget(box);

        QPushButton* ok = new QPushButton("ok");
        layout()->addWidget(ok);
        connect(ok, &QPushButton::clicked, this, [this]()
        {
           accept();
        });
    }

    QComboBox* comboBox() { return box; }

private:
    QComboBox* box;
};

To use the class object you can call exec to display it modally. Then you can verify whether the user accepted the choice by pressing the ok button and take proper action.

QStringList itemList({"item1", "item2", "item3"});
CustomDialog dialog(itemList);
if (dialog.exec() == QDialog::Accepted)
{
    // take proper action here
    qDebug() << dialog.comboBox()->currentText();
}

Similar approach is implemented in the QMessageBox class where a number of options can be specified to alter the displayed contents (for example button configuration or check box existance).

EDIT: To use the sample code in your own project you should put the latter section I posted into your on_pushButton_clicked() slot. Substitute the itemList with your color names list. Then put the CustomDialog class to a separate file which you include in main and you should be good to go.



来源:https://stackoverflow.com/questions/40919414/have-a-combobox-inside-a-message-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!