在消息框中有一个组合框 [英] Have a combobox inside a message box

查看:154
本文介绍了在消息框中有一个组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在消息框中创建一个组合框,并返回选择的值以供以后使用。

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() );
}


推荐答案

想要在单独的对话框窗口中显示一个组合框,供用户选择一些选项。

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

其中一个方法是子类 QDialog 。如果组合字段和一个按钮接受足够的类可以看起来如下:

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;
};

要使用类对象,可以调用 exec 以模态显示。然后,您可以按 ok 按钮验证用户是否接受该选择,并采取适当的措施。

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();
}

类似的方法在 QMessageBox class其中可以指定多个选项来更改显示的内容(例如按钮配置或复选框存在)。

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).

/ strong>
要在自己的项目中使用示例代码,应该将后面的部分放到 on_pushButton_clicked()插槽中。用您的颜色名称列表替换 itemList 。然后把 CustomDialog 类放到一个单独的文件,你包含在main,你应该很好去。

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.

这篇关于在消息框中有一个组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆