以下为用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 confirmOrder();

private:
    QComboBox *dishComboBox;
    QSpinBox *quantitySpinBox;
    QPushButton *confirmButton;
    QLabel *orderLabel;
    float totalAmount;

    void createUI();
};

#endif // MAINWINDOW_H

mainwindow.cpp文件:

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    totalAmount = 0.0;
    createUI();
}

MainWindow::~MainWindow()
{
}

void MainWindow::createUI()
{
    dishComboBox = new QComboBox(this);
    dishComboBox->addItem('Dish 1');
    dishComboBox->addItem('Dish 2');
    dishComboBox->addItem('Dish 3');
    dishComboBox->addItem('Dish 4');

    quantitySpinBox = new QSpinBox(this);
    quantitySpinBox->setRange(1, 10);

    confirmButton = new QPushButton('Confirm Order', this);
    connect(confirmButton, &QPushButton::clicked, this, &MainWindow::confirmOrder);

    orderLabel = new QLabel(this);
    orderLabel->setFixedSize(300, 200);
    orderLabel->setAlignment(Qt::AlignTop);
    orderLabel->setStyleSheet('border: 1px solid black;');

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(dishComboBox);
    layout->addWidget(quantitySpinBox);
    layout->addWidget(confirmButton);
    layout->addWidget(orderLabel);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
}

void MainWindow::confirmOrder()
{
    QString dish = dishComboBox->currentText();
    int quantity = quantitySpinBox->value();
    float amount = 0.0;

    if (dish == 'Dish 1')
        amount = 10.0;
    else if (dish == 'Dish 2')
        amount = 15.0;
    else if (dish == 'Dish 3')
        amount = 20.0;
    else if (dish == 'Dish 4')
        amount = 25.0;

    totalAmount += amount * quantity;

    QString orderText = orderLabel->text();
    orderText += dish + ' x ' + QString::number(quantity) + ' - Amount: ' + QString::number(amount * quantity) + '\n';
    orderLabel->setText(orderText);

    QMessageBox::information(this, 'Order Confirmation', 'Order placed successfully!');

    // Reset selection
    dishComboBox->setCurrentIndex(0);
    quantitySpinBox->setValue(1);
}

运行截图: 点菜程序界面截图

QT点菜程序设计:组件化封装、界面展示与订单确认

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

免费AI点我,无需注册和登录