QT-从Combobox选择颜色并绘制矩形



我想从下拉菜单中选择颜色,并基于该颜色,我想在窗口上绘制矩形。我可以绘制一个带有预定义颜色的矩形,但不确定如何从Combobox传递颜色。窗口上只绘制一个矩形,我想在窗口上绘制多个矩形。

因此,该过程是这样的。用户将单击按下按钮 -> ComboBox出现--->选择颜色 ->单击"确定",该颜色的矩形将出现在窗口上。

dialog.cpp

    Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}
Dialog::~Dialog()
{
    delete ui;
}
class CustomDialog : public QDialog
{
public:
    CustomDialog(const QStringList& items)
    {
        setLayout(new QHBoxLayout());
        box = new QComboBox;
        box->addItems(items);
        layout()->addWidget(box);
        connect(box, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(colorSelected(const QString&)));
        QPushButton* ok = new QPushButton("ok");
        layout()->addWidget(ok);
        connect(ok, &QPushButton::clicked, this, [this]()
        {
           accept();
        });
    }
    QComboBox* combobox() { return box; }
private:
    QComboBox* box;
};
void Dialog::on_pushButton_clicked()
{
    QStringList itemList({"Red", "Blue", "Green"});
    CustomDialog dialog(itemList);
   // connect(box, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(colorSelected(const QString&)));
    if (dialog.exec() == QDialog::Accepted)
    {
        scene = new QGraphicsScene(this);
        ui->graphicsView->setScene(scene);
        QBrush redBrush(Qt::red);
        QBrush blackBrush(Qt::black);
        QPen blackpen(Qt::black);
        blackpen.setWidth(3);
        rectangle = scene->addRect(10,10,100,100,blackpen,redBrush);
        rectangle->setFlag(QGraphicsItem::ItemIsMovable);
    }
}
void Dialog::colorSelected(const QString& text)
{
      const QColor selected =  colorMap[text];
}

上一篇文章没有解决我的问题。

除了上述内容外,我还建议使用项目数据保存颜色定义。看:

QComboBox::setItemData
QComboBox::itemData
QComboBox::currentData

组合盒中的每个项目都有两个组件;有显示的文本,然后有一个相关的Qvariant,这是项目数据。QVariant可以保留您的颜色定义,因此您不必单独存储它们。实际上,这超过两个,因为您可以根据需要定义尽可能多的用户角色,这将使您每个Commobox项目存储更多的数据元素。但是,出于您的目的,默认的userrole就足够了。

您的颜色定义将是:

void Dialog::colorSelected (const QString &text)
{
    const QColor selected = box->currentData().value <QColor> ();
    // do what you need with the color
}

如果您对彩色选择器不感兴趣,并且想要使用QComboBox的解决方案,则可以预先定义自己要使用的颜色集。

您可以声明地图,例如QMap<QString, QColor> colors;,它将在用字符串描述的键下保存颜色值。

然后,您应该定义所需的值。例如:

colors = 
{
    {"Red", QColor(255, 0, 0)},
    {"Green", QColor(0, 255, 0)},
    {"Blue", QColor(0, 0, 255)},
};

您可以轻松地使用此地图填充QComboBox的内容。很快写作:

box->addItems(colors.keys());

下一个操作取决于您何时需要知道颜色值。如果您想在用户选择后立即知道它,则需要制作适当的connect。例如:

connect(box, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(colorSelected(const QString&)));

colorSelected将是您处理所选颜色值的插槽:

void Dialog::colorSelected(const QString& text)
{
    const QColor selected = colors[text];
    // do what you need with the color
}

最新更新