QT 点菜程序设计:组件化封装实现菜单选择与数量控制
以下是一个简单的用 QT 设计的点菜程序的代码示例:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QComboBox>
#include <QSpinBox>
#include <QLabel>
#include <QGridLayout>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void updateTotalAmount();
private:
QComboBox *menuComboBox;
QSpinBox *quantitySpinBox;
QLabel *detailsLabel;
QLabel *totalAmountLabel;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
menuComboBox = new QComboBox;
menuComboBox->addItem('菜品1');
menuComboBox->addItem('菜品2');
menuComboBox->addItem('菜品3');
quantitySpinBox = new QSpinBox;
quantitySpinBox->setMinimum(1);
quantitySpinBox->setMaximum(10);
detailsLabel = new QLabel;
detailsLabel->setText('菜品详情');
totalAmountLabel = new QLabel;
totalAmountLabel->setText('总金额: 0');
connect(menuComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::updateTotalAmount);
connect(quantitySpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::updateTotalAmount);
QGridLayout *layout = new QGridLayout;
layout->addWidget(menuComboBox, 0, 0);
layout->addWidget(quantitySpinBox, 0, 1);
layout->addWidget(detailsLabel, 1, 0);
layout->addWidget(totalAmountLabel, 2, 0);
QWidget *centralWidget = new QWidget;
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
}
MainWindow::~MainWindow()
{
}
void MainWindow::updateTotalAmount()
{
QString selectedMenu = menuComboBox->currentText();
int quantity = quantitySpinBox->value();
// 根据选中的菜品和数量计算总金额
int totalAmount = 0;
if (selectedMenu == '菜品1') {
totalAmount = 10 * quantity;
} else if (selectedMenu == '菜品2') {
totalAmount = 20 * quantity;
} else if (selectedMenu == '菜品3') {
totalAmount = 30 * quantity;
}
totalAmountLabel->setText('总金额: ' + QString::number(totalAmount));
}
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
运行截图:

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