QT点菜程序:组件化封装,下拉菜单选菜,界面显示详情和总金额
#include
class DishesWidget : public QWidget { public: DishesWidget(QWidget* parent = nullptr) : QWidget(parent) { QVBoxLayout* layout = new QVBoxLayout(this);
// 菜品列表下拉菜单
QComboBox* dishesCombo = new QComboBox(this);
dishesCombo->addItem("鱼香肉丝");
dishesCombo->addItem("宫保鸡丁");
dishesCombo->addItem("红烧肉");
layout->addWidget(dishesCombo);
// 数量选择
QSpinBox* quantitySpin = new QSpinBox(this);
quantitySpin->setRange(1, 10);
layout->addWidget(quantitySpin);
// 确认选菜按钮
QPushButton* confirmButton = new QPushButton("确认选菜", this);
layout->addWidget(confirmButton);
// 菜单详情
QLabel* detailLabel = new QLabel(this);
layout->addWidget(detailLabel);
// 总金额
QLabel* totalLabel = new QLabel(this);
layout->addWidget(totalLabel);
// 连接确认选菜按钮的点击事件
connect(confirmButton, &QPushButton::clicked, this, [dishesCombo, quantitySpin, detailLabel, totalLabel]() {
QString dish = dishesCombo->currentText();
int quantity = quantitySpin->value();
QString detail = QString("菜品:%1 数量:%2").arg(dish).arg(quantity);
detailLabel->setText(detail);
// 计算总金额
int price = getPrice(dish);
int total = price * quantity;
totalLabel->setText(QString("总金额:%1").arg(total));
});
}
private: int getPrice(const QString& dish) { // 根据菜品名称获取价格,这里使用一个简单的映射 QMap<QString, int> prices; prices["鱼香肉丝"] = 25; prices["宫保鸡丁"] = 30; prices["红烧肉"] = 35; return prices.value(dish, 0); } };
int main(int argc, char** argv) { QApplication app(argc, argv);
DishesWidget widget; widget.show();
return app.exec(); }

原文地址: https://www.cveoy.top/t/topic/p9ha 著作权归作者所有。请勿转载和采集!