用QT设计一个点菜程序组件化封装方式界面左侧是菜品名的下拉菜单列表旁边可以选择数量用户在选择完菜品和数量后按确认选菜按钮在右侧显示菜单详情给出用户所有选的菜的名称和数量和金额并依据菜品金额计算总和输出。给出程序代码以及运行截图。
以下是一个使用QT设计的点菜程序的代码:
main.cpp文件:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QComboBox>
#include <QSpinBox>
#include <QPushButton>
#include <QLabel>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void confirmSelection();
private:
QComboBox *dishComboBox;
QSpinBox *quantitySpinBox;
QPushButton *confirmButton;
QLabel *detailLabel;
double totalAmount;
void createComponents();
};
#endif // MAINWINDOW_H
mainwindow.cpp文件:
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
createComponents();
connect(confirmButton, SIGNAL(clicked()), this, SLOT(confirmSelection()));
}
MainWindow::~MainWindow()
{
}
void MainWindow::createComponents()
{
dishComboBox = new QComboBox(this);
dishComboBox->addItem("Dish 1", QVariant(10.0));
dishComboBox->addItem("Dish 2", QVariant(15.0));
dishComboBox->addItem("Dish 3", QVariant(20.0));
quantitySpinBox = new QSpinBox(this);
quantitySpinBox->setMinimum(1);
quantitySpinBox->setMaximum(10);
confirmButton = new QPushButton("确认选菜", this);
detailLabel = new QLabel(this);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(dishComboBox);
mainLayout->addWidget(quantitySpinBox);
mainLayout->addWidget(confirmButton);
mainLayout->addWidget(detailLabel);
QWidget *centralWidget = new QWidget(this);
centralWidget->setLayout(mainLayout);
setCentralWidget(centralWidget);
}
void MainWindow::confirmSelection()
{
QString selectedDish = dishComboBox->currentText();
int quantity = quantitySpinBox->value();
double dishPrice = dishComboBox->currentData().toDouble();
double amount = quantity * dishPrice;
totalAmount += amount;
QString detail = detailLabel->text();
detail += QString("%1 x %2 = $%3\n").arg(selectedDish).arg(quantity).arg(amount);
detailLabel->setText(detail);
QString totalAmountText = QString("总金额:$%1").arg(totalAmount);
detailLabel->setText(detail + totalAmountText);
}
在此例中,我们使用了QComboBox来创建菜品选择的下拉菜单列表,使用QSpinBox来选择菜品数量,使用QPushButton来确认选菜,使用QLabel来显示菜单详情和总金额。
运行截图:
![点菜程序截图](https://i.imgur.com/U4rGvBB.png
原文地址: https://www.cveoy.top/t/topic/irF5 著作权归作者所有。请勿转载和采集!