使用QT完成水果计价界面和功能,如下图:
运行结果:
代码:
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QListWidgetItem>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void initUi();
public slots:void listWidgetFruitItemClickedSlotFun(QListWidgetItem *);void totalPriceCountSoltFun(double);
private:Ui::Widget *ui;
};
#endif // WIDGET_H
widge.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);//初始化ui界面this->initUi();//选中更新价格connect(ui->listWidgetFruit, SIGNAL(itemClicked(QListWidgetItem *)),\this, SLOT(listWidgetFruitItemClickedSlotFun(QListWidgetItem *)));connect(ui->dSpinBoxPrice, SIGNAL(valueChanged(double)), this, SLOT(totalPriceCountSoltFun(double)));connect(ui->dSpinBoxWeight, SIGNAL(valueChanged(double)), this, SLOT(totalPriceCountSoltFun(double)));}Widget::~Widget()
{delete ui;
}void Widget::initUi()
{//设置价格初值ui->dSpinBoxPrice->setSuffix("元/斤");ui->dSpinBoxPrice->setValue(0.0);//ui->dSpinBoxPrice->setMinimum(2.2);ui->dSpinBoxPrice->setMaximum(30.0);ui->dSpinBoxWeight->setSuffix("斤");ui->dSpinBoxWeight->setValue(0.0);ui->dSpinBoxWeight->setMaximum(50.0);ui->dSpinBoxTotalprice->setSuffix("元");ui->dSpinBoxTotalprice->setMaximum(1500.0);ui->dSpinBoxTotalprice->setValue(ui->dSpinBoxPrice->value() * ui->dSpinBoxWeight->value());//添加水果QString fruitName[] = {"苹果","香蕉","樱桃","椰子","哈密瓜","水蜜桃"};QString fruitIcon[] = {":/ico/Apple.ico",":/ico/Banana.ico",\":/ico/Cherry.ico",":/ico/Coconut.ico",\":/ico/Hami_melon.ico",":/ico/Juicy_peach.ico"};for (int i = 0;i<6;i++){QListWidgetItem *qFruit = new QListWidgetItem();qFruit->setText(fruitName[i]);qFruit->setIcon(QIcon(fruitIcon[i]));ui->listWidgetFruit->addItem(qFruit);}ui->listWidgetFruit->setViewMode(QListWidget::IconMode);
}void Widget::listWidgetFruitItemClickedSlotFun(QListWidgetItem *)
{//定制价格double price[] = {3.2, 2.3, 25.48, 15.0, 3.5, 10.8};//获取第几个被选中int index = ui->listWidgetFruit->currentRow();//更新价格ui->dSpinBoxPrice->setValue(price[index]);
}void Widget::totalPriceCountSoltFun(double)
{ui->dSpinBoxTotalprice->setValue(ui->dSpinBoxPrice->value() * ui->dSpinBoxWeight->value());
}