Organize source files into src subdirectories (gui/forms, gui/widgets, models, utils); replace magic numbers with ElementType enumeration in formproduct.cpp and formbudget.cpp (TODO completed); move mainwindow and related files to src/gui/

This commit is contained in:
Javi
2026-05-28 00:42:46 +02:00
parent b3b0116699
commit 3437103c28
72 changed files with 5893 additions and 0 deletions
+296
View File
@@ -0,0 +1,296 @@
#include "productdao.h"
#include "../mapplication.h"
bool ProductDAO::create(const QString& code, int type1, int type2, const QString& title,
const QString& description, const QString& familyId, const QString& unitId,
const QDate& dateUpdate, double realPrice, double discount, double purchasePrice,
double benefit, double tax, double salePrice, const QString& barcode,
const QByteArray& image, bool state, const QString& manufacturer,
const QString& gamma, double weight, double height, double width,
double lenght)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("INSERT INTO ELEMENT ("
"CODE, TYPE1, TYPE2, TITLE, DESCRIPTION, FAMILY_ID, UNIT_ID, "
"DATE_UPDATE, REAL_PRICE, DISCOUNT, PURCHASE_PRICE, BENEFIT, TAX, SALE_PRICE, "
"BARCODE, IMAGE, STATE, MANUFACTURER, GAMMA, "
"WEIGHT, HEIGHT, WIDTH, LENGHT"
") VALUES ("
":CODE, :TYPE1, :TYPE2, :TITLE, :DESCRIPTION, :FAMILY_ID, :UNIT_ID, "
":DATE_UPDATE, :REAL_PRICE, :DISCOUNT, :PURCHASE_PRICE, :BENEFIT, :TAX, :SALE_PRICE, "
":BARCODE, :IMAGE, :STATE, :MANUFACTURER, :GAMMA, "
":WEIGHT, :HEIGHT, :WIDTH, :LENGHT"
");");
qry.bindValue(":CODE", code);
qry.bindValue(":TYPE1", type1);
qry.bindValue(":TYPE2", type2);
qry.bindValue(":TITLE", title);
qry.bindValue(":DESCRIPTION", description);
qry.bindValue(":FAMILY_ID", familyId);
qry.bindValue(":UNIT_ID", unitId);
qry.bindValue(":DATE_UPDATE", dateUpdate);
qry.bindValue(":REAL_PRICE", realPrice);
qry.bindValue(":DISCOUNT", discount);
qry.bindValue(":PURCHASE_PRICE", purchasePrice);
qry.bindValue(":BENEFIT", benefit);
qry.bindValue(":TAX", tax);
qry.bindValue(":SALE_PRICE", salePrice);
qry.bindValue(":BARCODE", barcode);
qry.bindValue(":IMAGE", image);
qry.bindValue(":STATE", state);
qry.bindValue(":MANUFACTURER", manufacturer);
qry.bindValue(":GAMMA", gamma);
qry.bindValue(":WEIGHT", weight);
qry.bindValue(":HEIGHT", height);
qry.bindValue(":WIDTH", width);
qry.bindValue(":LENGHT", lenght);
bool success = qry.exec();
if (!success) {
qDebug() << "Error creating product:" << qry.lastError().text();
}
dApp->Enterprise().close();
return success;
}
bool ProductDAO::read(const QString& code, int& type1, int& type2, QString& title,
QString& description, QString& familyId, QString& unitId,
QDate& dateUpdate, double& realPrice, double& discount, double& purchasePrice,
double& benefit, double& tax, double& salePrice, QString& barcode,
QByteArray& image, bool& state, QString& manufacturer, QString& gamma,
double& weight, double& height, double& width, double& lenght)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("SELECT TYPE1, TYPE2, TITLE, DESCRIPTION, FAMILY_ID, UNIT_ID, "
"DATE_UPDATE, REAL_PRICE, DISCOUNT, PURCHASE_PRICE, BENEFIT, TAX, SALE_PRICE, "
"BARCODE, IMAGE, STATE, MANUFACTURER, GAMMA, "
"WEIGHT, HEIGHT, WIDTH, LENGHT "
"FROM ELEMENT WHERE CODE = :CODE");
qry.bindValue(":CODE", code);
bool success = qry.exec();
if (!success) {
qDebug() << "Error reading product:" << qry.lastError().text();
dApp->Enterprise().close();
return false;
}
if (qry.next()) {
type1 = qry.value(0).toInt();
type2 = qry.value(1).toInt();
title = qry.value(2).toString();
description = qry.value(3).toString();
familyId = qry.value(4).toString();
unitId = qry.value(5).toString();
dateUpdate = qry.value(6).toDate();
realPrice = qry.value(7).toDouble();
discount = qry.value(8).toDouble();
purchasePrice = qry.value(9).toDouble();
benefit = qry.value(10).toDouble();
tax = qry.value(11).toDouble();
salePrice = qry.value(12).toDouble();
barcode = qry.value(13).toString();
image = qry.value(14).toByteArray();
state = qry.value(15).toBool();
manufacturer = qry.value(16).toString();
gamma = qry.value(17).toString();
weight = qry.value(18).toDouble();
height = qry.value(19).toDouble();
width = qry.value(20).toDouble();
lenght = qry.value(21).toDouble();
} else {
success = false;
}
dApp->Enterprise().close();
return success;
}
bool ProductDAO::update(const QString& code, int type1, int type2, const QString& title,
const QString& description, const QString& familyId, const QString& unitId,
const QDate& dateUpdate, double realPrice, double discount, double purchasePrice,
double benefit, double tax, double salePrice, const QString& barcode,
const QByteArray& image, bool state, const QString& manufacturer,
const QString& gamma, double weight, double height, double width,
double lenght)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("UPDATE ELEMENT SET "
"TYPE1 = :TYPE1, TYPE2 = :TYPE2, TITLE = :TITLE, DESCRIPTION = :DESCRIPTION, FAMILY_ID = :FAMILY_ID, "
"UNIT_ID = :UNIT_ID, DATE_UPDATE = :DATE_UPDATE, REAL_PRICE = :REAL_PRICE, DISCOUNT = :DISCOUNT, "
"PURCHASE_PRICE = :PURCHASE_PRICE, BENEFIT = :BENEFIT, TAX = :TAX, SALE_PRICE = :SALE_PRICE, BARCODE = :BARCODE, IMAGE = :IMAGE, "
"STATE = :STATE, MANUFACTURER = :MANUFACTURER, GAMMA = :GAMMA, WEIGHT = :WEIGHT, HEIGHT = :HEIGHT, "
"WIDTH = :WIDTH, LENGHT = :LENGHT "
"WHERE CODE = :CODE");
);
qry.bindValue(":TYPE1", type1);
qry.bindValue(":TYPE2", type2);
qry.bindValue(":TITLE", title);
qry.bindValue(":DESCRIPTION", description);
qry.bindValue(":FAMILY_ID", familyId);
qry.bindValue(":UNIT_ID", unitId);
qry.bindValue(":DATE_UPDATE", dateUpdate);
qry.bindValue(":REAL_PRICE", realPrice);
qry.bindValue(":DISCOUNT", discount);
qry.bindValue(":PURCHASE_PRICE", purchasePrice);
qry.bindValue(":BENEFIT", benefit);
qry.bindValue(":TAX", tax);
qry.bindValue(":SALE_PRICE", salePrice);
qry.bindValue(":BARCODE", barcode);
qry.bindValue(":IMAGE", image);
qry.bindValue(":STATE", state);
qry.bindValue(":MANUFACTURER", manufacturer);
qry.bindValue(":GAMMA", gamma);
qry.bindValue(":WEIGHT", weight);
qry.bindValue(":HEIGHT", height);
qry.bindValue(":WIDTH", width);
qry.bindValue(":LENGHT", lenght);
qry.bindValue(":CODE", code);
bool success = qry.exec();
if (!success) {
qDebug() << "Error updating product:" << qry.lastError().text();
}
dApp->Enterprise().close();
return success;
}
bool ProductDAO::remove(const QString& code)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("DELETE FROM ELEMENT WHERE CODE = :CODE");
qry.bindValue(":CODE", code);
bool success = qry.exec();
if (!success) {
qDebug() << "Error deleting product:" << qry.lastError().text();
}
dApp->Enterprise().close();
return success;
}
bool ProductDAO::exists(const QString& code)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("SELECT COUNT(*) FROM ELEMENT WHERE CODE = :CODE");
qry.bindValue(":CODE", code);
bool success = qry.exec();
if (!success) {
qDebug() << "Error checking product existence:" << qry.lastError().text();
dApp->Enterprise().close();
return false;
}
bool exists = false;
if (qry.next()) {
exists = (qry.value(0).toInt() > 0);
}
dApp->Enterprise().close();
return exists;
}
QVector<QString> ProductDAO::getAllCodes()
{
QVector<QString> codes;
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("SELECT CODE FROM ELEMENT ORDER BY CODE");
bool success = qry.exec();
if (!success) {
qDebug() << "Error getting product codes:" << qry.lastError().text();
dApp->Enterprise().close();
return codes;
}
while (qry.next()) {
codes.append(qry.value(0).toString());
}
dApp->Enterprise().close();
return codes;
}
QVector<QPair<QString, double>> ProductDAO::getComposition(const QString& code)
{
QVector<QPair<QString, double>> composition;
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("SELECT ELEMENT_CODE, ELEMENT_AMOUNT FROM ELEMENTCOMPOSITION WHERE CODE = :CODE");
qry.bindValue(":CODE", code);
bool success = qry.exec();
if (!success) {
qDebug() << "Error getting product composition:" << qry.lastError().text();
dApp->Enterprise().close();
return composition;
}
while (qry.next()) {
composition.append(qMakePair(qry.value(0).toString(), qry.value(1).toDouble()));
}
dApp->Enterprise().close();
return composition;
}
bool ProductDAO::addCompositionElement(const QString& productCode, const QString& elementCode, double amount)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("INSERT INTO ELEMENTCOMPOSITION (CODE, ELEMENT_CODE, ELEMENT_AMOUNT) "
"VALUES (:CODE, :ELEMENT_CODE, :ELEMENT_AMOUNT)");
qry.bindValue(":CODE", productCode);
qry.bindValue(":ELEMENT_CODE", elementCode);
qry.bindValue(":ELEMENT_AMOUNT", amount);
bool success = qry.exec();
if (!success) {
qDebug() << "Error adding composition element:" << qry.lastError().text();
}
dApp->Enterprise().close();
return success;
}
bool ProductDAO::removeCompositionElement(const QString& productCode, const QString& elementCode)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("DELETE FROM ELEMENTCOMPOSITION WHERE CODE = :CODE AND ELEMENT_CODE = :ELEMENT_CODE");
qry.bindValue(":CODE", productCode);
qry.bindValue(":ELEMENT_CODE", elementCode);
bool success = qry.exec();
if (!success) {
qDebug() << "Error removing composition element:" << qry.lastError().text();
}
dApp->Enterprise().close();
return success;
}
bool ProductDAO::updateCompositionElement(const QString& productCode, const QString& elementCode, double amount)
{
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare("UPDATE ELEMENTCOMPOSITION SET ELEMENT_AMOUNT = :ELEMENT_AMOUNT "
"WHERE CODE = :CODE AND ELEMENT_CODE = :ELEMENT_CODE");
qry.bindValue(":ELEMENT_AMOUNT", amount);
qry.bindValue(":CODE", productCode);
qry.bindValue(":ELEMENT_CODE", elementCode);
bool success = qry.exec();
if (!success) {
qDebug() << "Error updating composition element:" << qry.lastError().text();
}
dApp->Enterprise().close();
return success;
}
+63
View File
@@ -0,0 +1,63 @@
#ifndef PRODUCTDAO_H
#define PRODUCTDAO_H
#include <QString>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QVector>
#include "../gui/formproduct.h"
#include "../data/sqltable.h"
class ProductDAO
{
public:
// Create a new product
static bool create(const QString& code, int type1, int type2, const QString& title,
const QString& description, const QString& familyId, const QString& unitId,
const QDate& dateUpdate, double realPrice, double discount, double purchasePrice,
double benefit, double tax, double salePrice, const QString& barcode,
const QByteArray& image, bool state, const QString& manufacturer,
const QString& gamma, double weight, double height, double width,
double lenght);
// Read a product by code
static bool read(const QString& code, int& type1, int& type2, QString& title,
QString& description, QString& familyId, QString& unitId,
QDate& dateUpdate, double& realPrice, double& discount, double& purchasePrice,
double& benefit, double& tax, double& salePrice, QString& barcode,
QByteArray& image, bool& state, QString& manufacturer, QString& gamma,
double& weight, double& height, double& width, double& lenght);
// Update an existing product
static bool update(const QString& code, int type1, int type2, const QString& title,
const QString& description, const QString& familyId, const QString& unitId,
const QDate& dateUpdate, double realPrice, double discount, double purchasePrice,
double benefit, double tax, double salePrice, const QString& barcode,
const QByteArray& image, bool state, const QString& manufacturer,
const QString& gamma, double weight, double height, double width,
double lenght);
// Delete a product
static bool remove(const QString& code);
// Check if product exists
static bool exists(const QString& code);
// Get all products
static QVector<QString> getAllCodes();
// Get product composition
static QVector<QPair<QString, double>> getComposition(const QString& code);
// Add composition element
static bool addCompositionElement(const QString& productCode, const QString& elementCode, double amount);
// Remove composition element
static bool removeCompositionElement(const QString& productCode, const QString& elementCode);
// Update composition element amount
static bool updateCompositionElement(const QString& productCode, const QString& elementCode, double amount);
};
#endif // PRODUCTDAO_H
+13
View File
@@ -0,0 +1,13 @@
#ifndef ELEMENTTYPE_H
#define ELEMENTTYPE_H
enum ElementType {
Composed = 0,
Material = 1,
ManPower = 2,
Machinery = 3,
Subcontracted = 4,
Other = 5
};
#endif // ELEMENTTYPE_H
+143
View File
@@ -0,0 +1,143 @@
#include "dialogcreateenterprise.h"
#include "ui_dialogcreateenterprise.h"
#include "sqltable.h"
#include "mapplication.h"
#include <QtSql>
dialogCreateEnterprise::dialogCreateEnterprise(QWidget *parent) :
QDialog(parent),
ui(new Ui::dialogCreateEnterprise)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true);
}
dialogCreateEnterprise::~dialogCreateEnterprise()
{
delete ui;
}
void dialogCreateEnterprise::on_pushBack_released()
{
}
void dialogCreateEnterprise::on_pushNext_released()
{
// TODO: guardar y crear la empresa
if(ui->editName->text().isEmpty())
{
return;
}
if(ui->editCIF->text().isEmpty())
{
return;
}
createEnterprise();
close();
}
void dialogCreateEnterprise::createEnterprise()
{
QString CIF = ui->editCIF->text().toUpper();
QString path = dApp->dataFolder() + CIF + QDir::separator();
QDir dir;
dir.mkpath(path);
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE", CIF);
database.setDatabaseName(path + CIF + ".db");
if(!database.open())
return;
// Crear la base de datos:
for(auto table : dbTables)
{
QSqlQuery qry(database);
if (!qry.exec(table))
{
// TODO: mandar un mensaje y repetir si es necesario
}
}
QString ENTERPRISES = "INSERT INTO ENTERPRISES ("
"NAME, CIF, DBNAME, PATH"
") VALUES ("
":NAME, :CIF, :DBNAME, :PATH"
");";
QString ENTERPRISESINFO = "INSERT INTO ENTERPRISESINFO ("
"NAME, CIF, ADDRESS, POSTCODE, CITY, PROVINCE, COUNTRY, PHONE, MOBILE, FAX, "
"EMAIL, WEB, CIF_COMMUNITY, IAE, CNAE, DCNAE, LOGO1, LOGO2"
") VALUES ("
":NAME, :CIF, :ADDRESS, :POSTCODE, :CITY, :PROVINCE, :COUNTRY, :PHONE, :MOBILE, :FAX, "
":EMAIL, :WEB, :CIF_COMMUNITY, :IAE, :CNAE, :DCNAE, :LOGO1, :LOGO2"
");";
QSqlQuery qry(database);
//QSqlQuery *qry = new QSqlQuery(dApp->getDBConnection());
qry.prepare(ENTERPRISESINFO);
qry.bindValue(":NAME", ui->editName->text());
qry.bindValue(":CIF", ui->editCIF->text());
qry.bindValue(":ADDRESS", ui->editAddress->toPlainText());
qry.bindValue(":POSTCODE", ui->editCP->text());
qry.bindValue(":CITY", ui->editCity->text());
qry.bindValue(":PROVINCE", ui->editProvince->text());
qry.bindValue(":COUNTRY", ui->editCountry->text());
qry.bindValue(":PHONE", ui->editPhone->text());
//qry.bindValue(":MOBILE", ui->edit->text());
qry.bindValue(":FAX", ui->editFax->text());
qry.bindValue(":EMAIL", ui->editEmail->text());
qry.bindValue(":WEB", ui->editWebside->text());
//qry.bindValue(":CIF_COMMUNITY", ui->edit->text());
//qry.bindValue(":IAE", ui->editName->text());
//qry.bindValue(":CNAE", ui->editName->text());
//qry.bindValue(":DCENAE", ui->editName->text());
//qry.bindValue(":LOGO1", ui->editName->text());
//qry.bindValue(":lOGO2", ui->editName->text());
if (!qry.exec())
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
return;
}
qry.prepare(DBInfoCommand);
qry.bindValue(":VERSION", dApp->applicationVersion().isEmpty() ? "0" : dApp->applicationVersion());
qry.bindValue(":SUBVERSION", "0");
if (!qry.exec())
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
return;
}
qry.clear();
qry.finish();
database.close();
QSqlDatabase::removeDatabase(CIF);
// 2. Poner la compañia en la lista:
dApp->EnterpriseList().open();
QSqlQuery qryList(dApp->EnterpriseList());
qryList.prepare(ENTERPRISES);
qryList.bindValue(":NAME", ui->editName->text());
qryList.bindValue(":CIF", ui->editCIF->text());
qryList.bindValue(":DBNAME", CIF);
qryList.bindValue(":PATH", path);
if (!qryList.exec())
{
qDebug() << "Error ejecutando el query: " << qryList.lastError().text() << "\n";
return;
}
dApp->Enterprise().close();
// 3. Abrir la empresa
dApp->openCompany(CIF);
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef DIALOGCREATEENTERPRISE_H
#define DIALOGCREATEENTERPRISE_H
#include <QDialog>
namespace Ui
{
class dialogCreateEnterprise;
}
class dialogCreateEnterprise : public QDialog
{
Q_OBJECT
public:
explicit dialogCreateEnterprise(QWidget *parent = 0);
~dialogCreateEnterprise();
private slots:
void on_pushNext_released();
void on_pushBack_released();
private:
Ui::dialogCreateEnterprise *ui;
void createEnterprise();
};
#endif // DIALOGCREATEENTERPRISE_H
+444
View File
@@ -0,0 +1,444 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>dialogCreateEnterprise</class>
<widget class="QDialog" name="dialogCreateEnterprise">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>550</width>
<height>500</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QFrame" name="frame_2">
<layout class="QGridLayout" name="gridLayout">
<item row="1" column="4">
<widget class="QLineEdit" name="editCIF">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="QLineEdit" name="lineEdit_2">
<property name="maximumSize">
<size>
<width>50</width>
<height>16777215</height>
</size>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Nombre/Razón social</string>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QLabel" name="label_3">
<property name="text">
<string>C.I.F.</string>
</property>
</widget>
</item>
<item row="2" column="2" colspan="5">
<widget class="QLineEdit" name="editName"/>
</item>
<item row="1" column="5">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Forma jurídica</string>
</property>
</widget>
</item>
<item row="1" column="6">
<widget class="QComboBox" name="comboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
<item>
<property name="text">
<string>New Item</string>
</property>
</item>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="label_13">
<property name="text">
<string>Código</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="label_12">
<property name="text">
<string>Nombre comercial</string>
</property>
</widget>
</item>
<item row="4" column="2" colspan="5">
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item row="1" column="0" rowspan="4">
<widget class="AvatarWidget" name="label_14">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>75</width>
<height>75</height>
</size>
</property>
<property name="frameShape">
<enum>QFrame::WinPanel</enum>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabGeneralInfo">
<attribute name="title">
<string>Datos generales</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QWidget" name="widget" native="true">
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="0">
<widget class="QLabel" name="label_6">
<property name="text">
<string>CP / Población</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_8">
<property name="text">
<string>Pais</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_7">
<property name="text">
<string>Provincia</string>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="QLineEdit" name="editCity"/>
</item>
<item row="3" column="1" colspan="2">
<widget class="QLineEdit" name="editProvince"/>
</item>
<item row="0" column="0" alignment="Qt::AlignTop">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Dirección</string>
</property>
</widget>
</item>
<item row="4" column="1" colspan="2">
<widget class="QLineEdit" name="editCountry"/>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="editCP">
<property name="maximumSize">
<size>
<width>150</width>
<height>16777215</height>
</size>
</property>
</widget>
</item>
<item row="0" column="1" colspan="2">
<widget class="QPlainTextEdit" name="editAddress">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>66</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>1</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(191, 191, 191);</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="QWidget" name="widget_4" native="true">
<layout class="QGridLayout" name="gridLayout_3">
<item row="2" column="0">
<widget class="QLabel" name="label_10">
<property name="text">
<string>Webside</string>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QLineEdit" name="editFax"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_11">
<property name="text">
<string>Email</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_9">
<property name="text">
<string>Teléfono / Fax</string>
</property>
</widget>
</item>
<item row="1" column="1" colspan="2">
<widget class="QLineEdit" name="editEmail"/>
</item>
<item row="2" column="1" colspan="2">
<widget class="QLineEdit" name="editWebside"/>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="editPhone"/>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<widget class="QWidget" name="tabOthers">
<attribute name="title">
<string>Otros datos</string>
</attribute>
<widget class="QWidget" name="widget_5" native="true">
<property name="geometry">
<rect>
<x>10</x>
<y>20</y>
<width>381</width>
<height>121</height>
</rect>
</property>
</widget>
</widget>
<widget class="QWidget" name="tab_2">
<attribute name="title">
<string>Page</string>
</attribute>
</widget>
</widget>
</item>
<item>
<widget class="QWidget" name="widget_3" native="true">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QPushButton" name="pushBack">
<property name="enabled">
<bool>false</bool>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<property name="text">
<string>Anterior</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushNext">
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<property name="text">
<string>Siguiente</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>AvatarWidget</class>
<extends>QLabel</extends>
<header>avatarwidget.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
+51
View File
@@ -0,0 +1,51 @@
#include "dialogopencompany.h"
#include "ui_dialogopencompany.h"
#include "companylistitemdelegate.h"
#include "mapplication.h"
#include <QStandardItemModel>
dialogOpenCompany::dialogOpenCompany(QWidget *parent) :
QDialog(parent),
ui(new Ui::dialogOpenCompany)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true);
QListView *view = ui->listView;
model = new QStandardItemModel();
CompanyListItemDelegate *listdelegate = new CompanyListItemDelegate();
view->setItemDelegate(listdelegate); //connect the delegate to view
view->setModel(model); //connect the model to view.
}
dialogOpenCompany::~dialogOpenCompany()
{
delete ui;
}
void dialogOpenCompany::setData(QString Name, QString CIF, QString path)
{
QStandardItem *item = new QStandardItem();
QIcon icon(":/new/prefix1/about.png");
item->setData(Name, Qt::DisplayRole); // Nombre
item->setData(CIF, Qt::UserRole); // CIF
item->setData(path, Qt::UserRole + 1); // path
model->appendRow(item);
}
void dialogOpenCompany::on_buttonOpen_released()
{
on_listView_doubleClicked(ui->listView->currentIndex());
}
void dialogOpenCompany::on_listView_doubleClicked(const QModelIndex &index)
{
if(!index.isValid())
return;
dApp->openCompany(index.data(Qt::UserRole).toString());
close();
}
+32
View File
@@ -0,0 +1,32 @@
#ifndef DIALOGOPENCOMPANY_H
#define DIALOGOPENCOMPANY_H
#include <QDialog>
class QStandardItemModel;
namespace Ui
{
class dialogOpenCompany;
}
class dialogOpenCompany : public QDialog
{
Q_OBJECT
public:
explicit dialogOpenCompany(QWidget *parent = nullptr);
~dialogOpenCompany();
void setData(QString Name, QString CIF, QString path);
private slots:
void on_buttonOpen_released();
void on_listView_doubleClicked(const QModelIndex &index);
private:
Ui::dialogOpenCompany *ui;
QStandardItemModel *model;
};
#endif // DIALOGOPENCOMPANY_H
+75
View File
@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>dialogOpenCompany</class>
<widget class="QDialog" name="dialogOpenCompany">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>400</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListView" name="listView">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
</widget>
</item>
<item>
<widget class="QWidget" name="widget" native="true">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>1</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonOpen">
<property name="text">
<string>Abrir</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
+52
View File
@@ -0,0 +1,52 @@
#include "formbase.h"
#include "ui_formbase.h"
formBase::formBase(QString aID, int aEditMode, QWidget *parent) :
QWidget(parent),
mDocumentID(aID),
mNeedSave(false),
ui(new Ui::formBase)
{
if(aID.isEmpty())
{
newDocument();
}
else
{
openDocument(aID);
}
}
formBase::~formBase()
{
delete ui;
}
void formBase::newDocument()
{
mEditMode = false;
}
void formBase::openDocument(QString id)
{
mEditMode = true;
}
void formBase::save()
{
}
bool formBase::needsave()
{
return mNeedSave;
}
void formBase::setEditMode(bool aMode)
{
mEditMode = aMode;
}
+35
View File
@@ -0,0 +1,35 @@
#ifndef FORMBASE_H
#define FORMBASE_H
#include <QWidget>
namespace Ui {
class formBase;
}
class formBase : public QWidget
{
Q_OBJECT
public:
explicit formBase(QString aID = "", int aEditMode = 0, QWidget *parent = nullptr);
~formBase();
virtual void newDocument() = 0;
virtual void openDocument(QString id) = 0;
virtual void save() = 0;
virtual bool needsave() = 0;
virtual void setEditMode(bool aMode) = 0;
virtual void closeDocument(){};
private:
Ui::formBase *ui;
protected:
QString mDocumentID;
bool mEditMode;
bool mNeedSave;
};
#endif // FORMBASE_H
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>formBase</class>
<widget class="QWidget" name="formBase">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>705</width>
<height>492</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
</widget>
<resources/>
<connections/>
</ui>
+27
View File
@@ -0,0 +1,27 @@
#include "formbaselist.h"
#include "ui_formbaselist.h"
#include <QResizeEvent>
FormBaseList::FormBaseList(QWidget *parent)
: QWidget(parent)
, ui(new Ui::FormBaseList)
{
ui->setupUi(this);
}
FormBaseList::~FormBaseList()
{
delete ui;
}
void FormBaseList::resizeEvent(QResizeEvent *event)
{
QStringList texts = { tr("Nuevo"), tr("Editar"), tr("Clonar"), tr("Borrar"), tr("Actualizar") };
QList<QPushButton*> buttons = { ui->buttonNew, ui->buttonEdit, ui->buttonClone, ui->buttonDelete, ui->buttonUpdate };
for (int i = 0; i < buttons.size(); ++i) {
int sz = event->size().width();
buttons[i]->setText(sz > 400 ? texts[i] : "");
}
}
+25
View File
@@ -0,0 +1,25 @@
#ifndef FORMBASELIST_H
#define FORMBASELIST_H
#include <QWidget>
namespace Ui {
class FormBaseList;
}
class FormBaseList : public QWidget
{
Q_OBJECT
public:
explicit FormBaseList(QWidget *parent = nullptr);
~FormBaseList();
protected:
void resizeEvent(QResizeEvent *event) override;
private:
Ui::FormBaseList *ui;
};
#endif // FORMBASELIST_H
+115
View File
@@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormBaseList</class>
<widget class="QWidget" name="FormBaseList">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>412</width>
<height>297</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QTableView" name="tableView">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QFrame" name="frame_2">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QPushButton" name="buttonNew">
<property name="text">
<string>Nuevo</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/add-file.svg</normaloff>:/resources/icons/add-file.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonEdit">
<property name="text">
<string>Editar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/pencil.svg</normaloff>:/resources/icons/pencil.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonClone">
<property name="text">
<string>Duplicar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/copy.svg</normaloff>:/resources/icons/copy.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonDelete">
<property name="text">
<string>Borrar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/delete.svg</normaloff>:/resources/icons/delete.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonUpdate">
<property name="text">
<string>Actualizar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/recycle.svg</normaloff>:/resources/icons/recycle.svg</iconset>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources>
<include location="../editabletreemodel.qrc"/>
</resources>
<connections/>
</ui>
+617
View File
@@ -0,0 +1,617 @@
#include "formbudget.h"
#include "ui_formbudget.h"
#include "qmtreeview.h"
#include "treemodel.h"
#include "treeitem.h"
#include "mapplication.h"
#include "../src/elementtype.h"
#include "widgetcomboboxpopuptable.h"
#include "itemnumberdelegate.h"
#include "itemtextdelegate.h"
#include "itemtextpopupdelegate.h"
#include "itemcomboboxdelegate.h"
#include <QStringList>
#include <QFile>
#include <QAction>
#include <QtSql>
formBudget::formBudget(QString aID, int amEditMode, QWidget *parent) :
formBase(aID, amEditMode, parent),
ui(new Ui::formBudget)
{
ui->setupUi(this);
QStringList headers;
headers << tr("Índice") << tr("Código") << tr("Título") << tr("Descriction")
<< tr("Cantidad") << tr("Cantidad total") << tr("Unidad")
<< tr("N. Precio Unitario")<< tr("N. Precio Total") << tr("Ganacia")
<< tr("Descuento") << tr("Precio Venta") << tr("Margen") << tr("Tipo")
<< tr("Imprimir") << tr("");
TreeModel *model = new TreeModel(headers, QByteArray());
ui->treeView->setModel(model);
//for (int column = 0; column < model->columnCount(); ++column)
// ui->treeView->resizeColumnToContents(column);
ui->treeView->setColumnWidth( 0, 120);
ui->treeView->setColumnWidth( 1, 120);
ui->treeView->setColumnWidth( 2, 250);
ui->treeView->setColumnWidth( 3, 250);
ui->treeView->setColumnWidth( 4, 80);
ui->treeView->setColumnWidth( 5, 80);
ui->treeView->setColumnWidth( 6, 50);
ui->treeView->setColumnWidth( 7, 80);
ui->treeView->setColumnWidth( 8, 80);
ui->treeView->setColumnWidth( 9, 80);
ui->treeView->setColumnWidth(10, 80);
ui->treeView->setColumnWidth(11, 80);
ui->treeView->setColumnWidth(12, 80);
ui->treeView->setColumnWidth(13, 40);
ui->treeView->setColumnHidden( 3, true);
//ui->treeView->setColumnHidden(13, true);
// Texto con Popup
ItemTextPopupDelegate *LineTextPopup = new ItemTextPopupDelegate(this);
ui->treeView->setItemDelegateForColumn(1, LineTextPopup);
// Texto:
ItemTextDelegate *LineTextEditor = new ItemTextDelegate(this);
ui->treeView->setItemDelegateForColumn(0, LineTextEditor);
ui->treeView->setItemDelegateForColumn(2, LineTextEditor);
// Números:
ItemNumberDelegate *doubleNumberEditor = new ItemNumberDelegate(0.0, 999999.99, 0.05, 2, this);
ui->treeView->setItemDelegateForColumn(4, doubleNumberEditor);
ui->treeView->setItemDelegateForColumn(7, doubleNumberEditor);
ui->treeView->setItemDelegateForColumn(9, doubleNumberEditor);
ui->treeView->setItemDelegateForColumn(10, doubleNumberEditor);
// Combobox:
ItemComboboxDelegate *ComboboxEditor = new ItemComboboxDelegate(this);
ui->treeView->setItemDelegateForColumn(6, ComboboxEditor);
connect(model, &TreeModel::dataChanged, this, &formBudget::on_ModelSetData);
// Prueba:
connect(dApp, &QApplication::focusChanged, this, [=](QWidget* old, QWidget* now)
{
//qDebug() << "old: " << old << "\n" << "new: " << now;
if (!this->isAncestorOf(old))
qDebug() << "Se deshabilita la toolbox";
//Q_UNUSED(old);
//if (now != this && !this->isAncestorOf(now))
if (now == this && !this->isAncestorOf(now))
{
//hide();
qDebug() << "Se habilita la toolbox";
}
});
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
if (qry.exec(QString("SELECT ID FROM SALEPROPOSAL ORDER BY ID DESC LIMIT 1;")))
{
int val = 0;
while(qry.next())
val = qry.value(qry.record().indexOf("ID")).toInt();
ui->editCode->setText(QString("(PRO%1)").arg(val + 1));
}
dApp->Enterprise().close();
}
formBudget::~formBudget()
{
delete ui;
}
void formBudget::setupTreeView()
{
QStringList headers = {
tr("Índice"), tr("Código"), tr("Título"), tr("Descripción"),
tr("Cantidad"), tr("Cantidad total"), tr("Unidad"),
tr("N. Precio Unitario"), tr("N. Precio Total"), tr("Ganacia"),
tr("Descuento"), tr("Precio Venta"), tr("Margen"), tr("Tipo"),
tr("Imprimir"), tr("")
};
m_treeModel = new TreeModel(headers, QByteArray(), this);
ui->treeView->setModel(m_treeModel);
// Configurar anchos de columna
QVector<int> widths = {120, 120, 250, 250, 80, 80, 50, 80, 80, 80, 80, 80, 80, 40};
for (int i = 0; i < widths.size(); ++i) {
ui->treeView->setColumnWidth(i, widths[i]);
}
ui->treeView->setColumnHidden(3, true);
// Configurar delegados
setupDelegates();
}
void formBudget::setupDelegates()
{
// Texto con Popup
auto* lineTextPopup = new ItemTextPopupDelegate(this);
ui->treeView->setItemDelegateForColumn(1, lineTextPopup);
// Texto simple
auto* lineTextEditor = new ItemTextDelegate(this);
ui->treeView->setItemDelegateForColumn(0, lineTextEditor);
ui->treeView->setItemDelegateForColumn(2, lineTextEditor);
// Números
auto* doubleNumberEditor = new ItemNumberDelegate(0.0, 999999.99, 0.05, 2, this);
ui->treeView->setItemDelegateForColumn(4, doubleNumberEditor);
ui->treeView->setItemDelegateForColumn(7, doubleNumberEditor);
ui->treeView->setItemDelegateForColumn(9, doubleNumberEditor);
ui->treeView->setItemDelegateForColumn(10, doubleNumberEditor);
// Combobox
auto* comboboxEditor = new ItemComboboxDelegate(this);
ui->treeView->setItemDelegateForColumn(6, comboboxEditor);
connect(m_treeModel, &TreeModel::dataChanged,
this, &formBudget::onModelDataChanged);
}
void formBudget::setupConnections()
{
connect(ui->buttonInsertRow, &QPushButton::released,
this, &formBudget::insertRow);
connect(ui->buttonInsertChild, &QPushButton::released,
this, &formBudget::insertChild);
connect(ui->buttonRemoveRow, &QPushButton::released,
this, &formBudget::removeRow);
// ... otras conexiones ...
}
void formBudget::initializeDocument()
{
if (m_dbUtils.isConnected()) {
QString lastId = m_dbUtils.getLastDocumentId("SALEPROPOSAL");
ui->editCode->setText(QString("(PRO%1)").arg(lastId.toInt() + 1));
}
}
void formBudget::newDocument()
{
}
void formBudget::openDocument(QString id)
{
formBase::openDocument(id);
}
void formBudget::save()
{
QString budget;
QString budgetdata;
if(mEditMode == false)
{
budget = "INSERT INTO SALEPROPOSAL ("
"ID, TYPE, CODE, TITLE, VERSION, "
"CUSTOMER_CODE, CUSTOMER_NAME, PROJECT_CODE, PROJECT_TITLE, "
"COST, PRICE, TAX, STATE, STATE_NUMBER, DESCRIPTION, "
"CREATEDAT, VALIDUNTILL, DELIVERY_DATE, CREATEDBY"
") VALUES ("
":ID, :TYPE, :CODE, :TITLE, :VERSION, "
":CUSTOMER_CODE, :CUSTOMER_NAME, :PROJECT_CODE, :PROJECT_TITLE, "
":COST, :PRICE, :TAX, :STATE, :STATE_NUMBER, :DESCRIPTION, "
":CREATEDAT, :VALIDUNTILL, :DELIVERY_DATE, :CREATEDBY"
");";
budgetdata = "INSERT INTO SALEPROPOSALDATA ("
"ID, SALEDOCUMENT_CODE, VERSION, NODEINDEX, "
"ELEMENT_CODE, ELEMENT_TYPE, ELEMENT_INDEX, ELEMENT_TITLE, ELEMENT_DESCRIPTION, "
"ELEMENT_UNIT_AMOUNT, ELEMENT_TOTAL_AMOUNT, ELEMENT_UNIT, ELEMENT_PRICE, "
"BENEFIT, DISCOUNT, TAX, PRINT, "
"CREATEDAT, CREATEDBY"
") VALUES ("
":ID, :SALEDOCUMENT_CODE, :VERSION, :NODEINDEX, "
":ELEMENT_CODE, :ELEMENT_TYPE, :ELEMENT_INDEX, :ELEMENT_TITLE, :ELEMENT_DESCRIPTION, "
":ELEMENT_UNIT_AMOUNT, :ELEMENT_TOTAL_AMOUNT, :ELEMENT_UNIT, :ELEMENT_PRICE, "
":BENEFIT, :DISCOUNT, :TAX, :PRINT, "
":CREATEDAT, :CREATEDBY"
");";
}
else
{
budget = "UPDATE SALEPROPOSAL SET "
":ID, :TYPE, :CODE, :TITLE, :VERSION, "
":CUSTOMER_CODE, :CUSTOMER_NAME, :PROJECT_CODE, :PROJECT_TITLE, "
":COST, :PRICE, :TAX, :STATE, :STATE_NUMBER, :DESCRIPTION, "
":CREATEDAT, :VALIDUNTILL, :DELIVERY_DATE, :CREATEDBY "
"WHERE CODE = :CODE"
";";
budgetdata = "UPDATE SALEPROPOSALDATA SET "
":ID, :SALEDOCUMENT_CODE, :VERSION, :NODEINDEX, "
":ELEMENT_CODE, :ELEMENT_TYPE, :ELEMENT_INDEX, :ELEMENT_TITLE, :ELEMENT_DESCRIPTION, "
":ELEMENT_UNIT_AMOUNT, :ELEMENT_TOTAL_AMOUNT, :ELEMENT_UNIT, :ELEMENT_PRICE, "
":BENEFIT, :DISCOUNT, :TAX, :PRINT, "
":CREATEDAT, :CREATEDBY "
"WHERE CODE = :CODE"
";";
}
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
// 1. Guardar los datos:
QAbstractItemModel *model = ui->treeView->model();
// Borrar toda las filas al final que están vacias
// -- de momento se hace chequeando si la columna 13 está vacía
/*
int count = model->rowCount() - 1;
for (int i = model->rowCount() - 1; i >= 0; i--)
{
count = i;
QString dat = model->index(i, 13).data().toString();
if(!dat.isEmpty())
break;
}
for (int i = 0; i <= count; i++)
{
qry.prepare(budgetdata);
qry.bindValue(":ID", i);
qry.bindValue(":SALEDOCUMENT_CODE", ui->editCode->text());
qry.bindValue(":VERSION", ui->editVersion->currentText());
qry.bindValue(":NODEINDEX", model->index(i, 0).data().toString());
qry.bindValue(":ELEMENT_CODE", model->index(i, 1).data().toString());
qry.bindValue(":ELEMENT_TYPE", model->index(i, 13).data().toString());
qry.bindValue(":ELEMENT_TITLE", model->index(i, 2).data().toString());
qry.bindValue(":ELEMENT_DESCRIPTION", model->index(i, 3).data().toString());
qry.bindValue(":ELEMENT_UNIT_AMOUNT", model->index(i, 4).data().toDouble());
//qry.bindValue(":ELEMENT_TOTAL_AMOUNT", model->index(i, 2).data().toDouble());
qry.bindValue(":ELEMENT_UNIT", model->index(i, 6).data().toString());
qry.bindValue(":ELEMENT_PRICE", model->index(i, 7).data().toString());
qry.bindValue(":BENEFIT", model->index(i, 9).data().toString());
qry.bindValue(":DISCOUNT", model->index(i, 10).data().toString());
//qry.bindValue(":TAX", model->index(i, 10).data().toString());
//qry.bindValue(":PRINT", model->index(i, 10).data().toBool());
if(!qry.exec())
{
qDebug() << "" << qry.lastError().text();
continue;
}
}
*/
// 2. Si todo fue bien, guardar el documento:
qry.prepare(budget);
//qry.bindValue(":ID",);
qry.bindValue(":TYPE", "");
qry.bindValue(":CODE", ui->editCode->text());
qry.bindValue(":TITLE", ui->editTitle->text());
qry.bindValue(":VERSION", ui->editVersion->currentText());
qry.bindValue(":CUSTOMER_CODE", ui->editClientCode->currentText());
qry.bindValue(":CUSTOMER_NAME", ui->editClientName->text());
qry.bindValue(":PROJECT_CODE", ui->editProjectCode->currentText());
qry.bindValue(":PROJECT_TITLE", ui->editProjectName->text());
qry.bindValue(":COST", ui->editCost->text());
qry.bindValue(":PRICE", ui->editPrice->text());
//qry.bindValue(":TAX", );
qry.bindValue(":STATE", ui->editPrice->text());
qry.bindValue(":STATE_NUMBER", ui->editPrice->text());
//qry.bindValue(":DESCRIPTION", );
qry.bindValue(":CREATEDAT", ui->editdateCreated->text());
qry.bindValue(":VALIDUNTILL", ui->editdateValidUntill->text());
//qry.bindValue(":DELIVERY_DATE", ui->editPrice->text());
//qry.bindValue(":CREATEDBY", ui->editPrice->text());
if(!qry.exec())
{
qDebug() << "" << qry.lastError().text();
}
else
mEditMode = true;
dApp->Enterprise().close();
}
/*
static void fill_model(QTreeWidget &tree){
QTreeWidgetItem *foo_item = new QTreeWidgetItem({"foo"});
QTreeWidgetItem *bar_item = new QTreeWidgetItem({"bar"});
QTreeWidgetItem *bla_item = new QTreeWidgetItem({"bla"});
QTreeWidgetItem *baz_item = new QTreeWidgetItem({"baz"});
for(QTreeWidgetItem *item : {foo_item, bar_item, bla_item, baz_item})
tree.addTopLevelItem(item);
QTreeWidgetItem *beer_item = new QTreeWidgetItem({"beer"});
QTreeWidgetItem *beer_child_item = new QTreeWidgetItem({"beer_child"});
QTreeWidgetItem *ice_item = new QTreeWidgetItem({"ice"});
for(QTreeWidgetItem *item : {beer_item, ice_item})
bar_item->addChild(item);
beer_item->addChild(beer_child_item);
beer_child_item->addChild(new QTreeWidgetItem({"beer_child_child"}));
}
static void save_to_db(const QString & tablename, QTreeWidgetItem* parent, int parent_id=0){
for(int i=0; i< parent->childCount(); ++i){
QTreeWidgetItem *child_item = parent->child(i);
QSqlQuery query(QString("INSERT INTO %1 (parentId, name) VALUES (?, ?)").arg(tablename));
if(parent_id != 0)
query.bindValue(0, parent_id);
query.bindValue(1, child_item->text(0));
if(!query.exec())
qDebug()<< query.lastError().text();
save_to_db(tablename, child_item, query.lastInsertId().toInt());
}
}
*/
void formBudget::saveModel(QSqlQuery qry, QString aCommand, QAbstractItemModel *aModel, int aLevel)
{
//QObjectList list = aModel->parent()->children();
//for (auto aChil : list)
for (int i = 0; i <= aModel->rowCount() - 1; i++)
{
qry.prepare(aCommand);
qry.bindValue(":ID", i);
qry.bindValue(":SALEDOCUMENT_CODE", ui->editCode->text());
qry.bindValue(":VERSION", ui->editVersion->currentText());
qry.bindValue(":NODEINDEX", aModel->index(i, 0).data().toString());
qry.bindValue(":ELEMENT_CODE", aModel->index(i, 1).data().toString());
qry.bindValue(":ELEMENT_TYPE", aModel->index(i, 13).data().toString());
qry.bindValue(":ELEMENT_TITLE", aModel->index(i, 2).data().toString());
qry.bindValue(":ELEMENT_DESCRIPTION", aModel->index(i, 3).data().toString());
qry.bindValue(":ELEMENT_UNIT_AMOUNT", aModel->index(i, 4).data().toDouble());
//qry.bindValue(":ELEMENT_TOTAL_AMOUNT", aModel->index(i, 2).data().toDouble());
qry.bindValue(":ELEMENT_UNIT", aModel->index(i, 6).data().toString());
qry.bindValue(":ELEMENT_PRICE", aModel->index(i, 7).data().toString());
qry.bindValue(":BENEFIT", aModel->index(i, 9).data().toString());
qry.bindValue(":DISCOUNT", aModel->index(i, 10).data().toString());
//qry.bindValue(":TAX", aModel->index(i, 10).data().toString());
//qry.bindValue(":PRINT", aModel->index(i, 10).data().toBool());
if(!qry.exec())
{
qDebug() << "" << qry.lastError().text();
continue;
}
if(aModel->index(i, 13).data().toString() == "CO")
{
//QAbstractItemModel * childModel = aModel->index(i, 13).child(0, 0);
//saveModel(qry, aCommand, childModel, aLevel + 1);
}
}
}
bool formBudget::needsave()
{
return formBase::needsave();
}
void formBudget::setEditMode(bool aMode)
{
formBase::setEditMode(aMode);
}
void formBudget::closeDocument()
{
if(mNeedSave)
{
}
save();
}
void formBudget::on_editPrice_textChanged(const QString &arg1)
{
}
void formBudget::on_buttonInsertRow_released()
{
ui->treeView->insertRow();
}
void formBudget::on_buttonInsertChild_released()
{
QModelIndex selindex = ui->treeView->selectionModel()->currentIndex();
QAbstractItemModel *treemodel = ui->treeView->model();
ui->treeView->insertChild();
QModelIndex child = treemodel->index(selindex.row(), 13, selindex.parent());
treemodel->setData(child, QVariant("CO"), Qt::EditRole);
}
void formBudget::on_buttonRemoveRow_released()
{
ui->treeView->removeRow();
}
void formBudget::on_buttonMaterials_released()
{
ui->treeView->insertRow();
setLineType("MT", ui->treeView->selectionModel()->currentIndex());
}
void formBudget::on_buttoMachinary_released()
{
ui->treeView->insertRow();
setLineType("MQ", ui->treeView->selectionModel()->currentIndex());
}
void formBudget::on_buttonManpower_released()
{
ui->treeView->insertRow();
setLineType("MO", ui->treeView->selectionModel()->currentIndex());
}
void formBudget::on_buttonPercent_released()
{
ui->treeView->insertRow();
setLineType("%", ui->treeView->selectionModel()->currentIndex());
}
void formBudget::setLineType(QString type, QModelIndex index)
{
setCellText(type, index, 13);
}
void formBudget::setCellText(QString val, QModelIndex index, int col)
{
QAbstractItemModel *treemodel = ui->treeView->model();
QModelIndex child = treemodel->index(index.row(), col, index.parent().isValid() ? index.parent() : QModelIndex());
treemodel->setData(child, QVariant(val), Qt::EditRole);
}
bool formBudget::InsertElement(QString ID, QModelIndex index)
{
if (ID.isEmpty())
return false;
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
if (qry.exec(QString("SELECT * FROM ELEMENT WHERE CODE = '%1';").arg(ID)))
{
qry.first();
setCellText(qry.value(qry.record().indexOf("TITLE")).toString(), index, 2); // TITLE
setCellText(qry.value(qry.record().indexOf("DESCRIPTION")).toString(), index, 3); // DESCRIPTION
setCellText(qry.value(qry.record().indexOf("UNIT_ID")).toString(), index, 6); // UNIT
if (qry.value(qry.record().indexOf("TYPE1")).toInt() == 0)
{
QSqlQuery comp = QSqlQuery(dApp->Enterprise());
QAbstractItemModel *treemodel = ui->treeView->model();
if (comp.exec(QString("SELECT * FROM ELEMENTCOMPOSITION WHERE CODE = '%1';").arg(ID)))
{
QList<QPair<QString, QString> > list;
while(comp.next())
{
list.append(qMakePair(comp.value(comp.record().indexOf("ELEMENT_CODE")).toString(),
comp.value(comp.record().indexOf("ELEMENT_AMOUNT")).toString()));
}
int row = 0;
while (row < list.size())
{
if(!treemodel->insertRow(treemodel->rowCount(index), treemodel->index(index.row(), 0, index.parent())))
break;
qDebug() << treemodel->rowCount(index);
QModelIndex child = treemodel->index(row, 0, treemodel->index(index.row(), 0, index.parent()));
setCellText(list.at(row).first, child, 1);
setCellText(list.at(row).second, child, 4); //AMOUNT*/
row++;
}
}
}
else
{
setCellText(qry.value(qry.record().indexOf("PURCHASE_PRICE")).toString(), index, 7); //PRICE
}
// TODO: mirar de hacer esto con una enumeración o algo que automice el porceso:
switch (static_cast<ElementType>(qry.value(qry.record().indexOf("TYPE1")).toInt()))
{
case ElementType::Composed:
setLineType("CO", index); // type
break;
case ElementType::Material:
setLineType("MT", index); // type
break;
case ElementType::ManPower:
setLineType("MO", index); // type
break;
case ElementType::Machinery:
setLineType("MQ", index); // type
break;
default:
break;
}
}
else
{
qDebug() << qry.lastError().text();
}
dApp->Enterprise().close();
return false;
}
void formBudget::on_buttonValidate_released()
{
// TODO: generar el código definitivo
mDocumentID = ui->editCode->text();
setWindowTitle(mDocumentID);
QTabWidget * prt = static_cast<QTabWidget*>(parent()->parent());
prt->setTabText(prt->currentIndex(), mDocumentID);
}
void formBudget::on_buttonSave_released()
{
save();
}
void formBudget::on_ModelSetData(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
if(mEditMode)
return;
Q_UNUSED(bottomRight);
if(topLeft.column() == 1)
{
qDebug() << topLeft.data().toString();
InsertElement(topLeft.data().toString(), topLeft);
}
}
void formBudget::focusInEvent(QFocusEvent *event)
{
qDebug() << "focusInEvent";
}
void formBudget::focusOutEvent(QFocusEvent *event)
{
qDebug() << "focusOutEvent";
}
void formBudget::on_tabWidget_currentChanged(int index)
{
if (index == 1)
{
ui->ToolbarLines->setVisible(true);
}
else
{
ui->ToolbarLines->setVisible(false);
}
}
+68
View File
@@ -0,0 +1,68 @@
#ifndef FORMBUDGET_H
#define FORMBUDGET_H
#include "formbase.h"
#include <QWidget>
class QString;
class TreeItem;
class QSqlQuery;
class QAbstractItemModel;
class TreeModel;
namespace Ui
{
class formBudget;
}
class formBudget : public formBase
{
Q_OBJECT
public:
explicit formBudget(QString aID = "", int aEditMode = 0, QWidget *parent = nullptr);
~formBudget() override;
//void openDocument(QString id);
void newDocument() override;
void openDocument(QString id) override;
void save() override;
bool needsave() override;
void setEditMode(bool aMode) override;
void closeDocument() override;
private slots:
void on_editPrice_textChanged(const QString &arg1);
void on_buttonInsertRow_released();
void on_buttonInsertChild_released();
void on_buttonPercent_released();
void on_buttonRemoveRow_released();
void on_buttonMaterials_released();
void on_buttoMachinary_released();
void on_buttonManpower_released();
void on_buttonValidate_released();
void on_buttonSave_released();
void on_ModelSetData(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles);
void on_tabWidget_currentChanged(int index);
private:
TreeModel *m_treeModel;
Ui::formBudget *ui;
void setLineType(QString type, QModelIndex index);
void setCellText(QString val, QModelIndex index, int col);
bool InsertElement(QString ID, QModelIndex index);
void saveModel(QSqlQuery qry, QString aCommand, QAbstractItemModel *aModel, int aLevel);
void setupTreeView();
void setupDelegates();
void setupConnections();
void initializeDocument();
protected:
virtual void focusInEvent(QFocusEvent *event) override;
virtual void focusOutEvent(QFocusEvent *event) override;
};
#endif // FORMBUDGET_H
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
#include "formbudgetlist.h"
#include "ui_formbudgetlist.h"
FormBudgetList::FormBudgetList(FormBaseList *parent)
: FormBaseList(parent)
, ui(new Ui::FormBudgetList)
{
ui->setupUi(this);
}
FormBudgetList::~FormBudgetList()
{
delete ui;
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef FORMBUDGETLIST_H
#define FORMBUDGETLIST_H
#include <QWidget>
#include <gui/formbaselist.h>
namespace Ui {
class FormBudgetList;
}
class FormBudgetList : public FormBaseList
{
Q_OBJECT
public:
explicit FormBudgetList(FormBaseList *parent = nullptr);
~FormBudgetList();
private:
Ui::FormBudgetList *ui;
};
#endif // FORMBUDGETLIST_H
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormBudgetList</class>
<widget class="QWidget" name="FormBudgetList">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
</widget>
<resources/>
<connections/>
</ui>
+181
View File
@@ -0,0 +1,181 @@
#include "formelementlist.h"
#include "qpainter.h"
#include "ui_formelementlist.h"
#include "formproduct.h"
#include "mainwindow.h"
#include "mapplication.h"
#include "msqlquerymodel.h"
#include "utils/filtertableheader.h"
#include "gui/formbaselist.h"
#include <QDrag>
formElementList::formElementList(QWidget *parent) :
QWidget(parent),
ui(new Ui::formElementList)
{
ui->setupUi(this);
mModel = new MSqlQueryModel(this);
ui->tableView->setModel(mModel);
updateList();
ui->tableView->setColumnWidth(0, 150);
ui->tableView->setColumnWidth(1, 80);
ui->tableView->setColumnWidth(2, 120);
ui->tableView->setColumnWidth(3, 350);
ui->tableView->setColumnWidth(4, 80);
ui->tableView->setColumnWidth(5, 80);
ui->tableView->setColumnWidth(6, 40);
// Set up filter row
auto *m_tableHeader = new FilterTableHeader(ui->tableView);
ui->tableView->setHorizontalHeader(m_tableHeader);
m_tableHeader->setFilter(0, "");
m_tableHeader->setFocusColumn(0);
ui->tableView->horizontalHeader()->model()->setHeaderData(0, Qt::Horizontal, tr("Tipo"));
ui->tableView->horizontalHeader()->model()->setHeaderData(1, Qt::Horizontal, tr("Clase"));
ui->tableView->horizontalHeader()->model()->setHeaderData(2, Qt::Horizontal, tr("Código"));
ui->tableView->horizontalHeader()->model()->setHeaderData(3, Qt::Horizontal, tr("Resumen"));
ui->tableView->horizontalHeader()->model()->setHeaderData(4, Qt::Horizontal, tr("Coste"));
ui->tableView->horizontalHeader()->model()->setHeaderData(5, Qt::Horizontal, tr("Venta"));
ui->tableView->horizontalHeader()->model()->setHeaderData(6, Qt::Horizontal, tr("Activo"));
ui->tableView->setDragEnabled(true); // Habilita el drag
connect(ui->tableView, &QTableView::pressed, this, &formElementList::startDrag);
}
formElementList::~formElementList()
{
delete ui;
}
void formElementList::updateList()
{
dApp->Enterprise().open();
mModel->setQuery("SELECT TYPE1, TYPE2, CODE, TITLE, PURCHASE_PRICE, SALE_PRICE, STATE FROM ELEMENT" /*" ORDER BY CODE ASC"*/,
dApp->Enterprise());
dApp->Enterprise().close();
}
void formElementList::on_buttonNew_released()
{
formProduct *form = dApp->mainWindow()->createFormProduct(); // sustistuir por Mainwindow::createFormProduct();
form->show();
}
void formElementList::on_buttonEdit_released()
{
openDocument(ui->tableView->currentIndex());
}
void formElementList::on_buttonClone_released()
{
}
void formElementList::on_buttonDelete_released()
{
QModelIndex index = ui->tableView->currentIndex();
QAbstractItemModel *model = const_cast<QAbstractItemModel*>(index.model()); // Obtén el modelo asociado
if (index.column() != 0)
{
//index = index.parent().child(index.row(), 0);
index = model->index(index.row(), 0, index.parent());
}
QString ID = index.data().toString();
QModelIndex parentIndex = index.parent();
QModelIndex childIndex = model->index(index.row(), 2, parentIndex); // Obtén el índice del hijo
int type = childIndex.data().toInt(); // Accede al dato
//int type = index.parent().child(index.row(), 2).data().toInt();
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
// Check if it's a composed element (TYPE1 = 0) and delete its composition first
QModelIndex parentIndex = index.parent();
QModelIndex childIndex = model->index(index.row(), 2, parentIndex); // Obtén el índice del hijo
int type = childIndex.data().toInt(); // Accede al dato
if (type == 0) // ElementType::Composed
{
// Delete composition elements first
if(!qry.exec(QString("DELETE FROM ELEMENTCOMPOSITION WHERE CODE = '%1';").arg(ID)))
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
goto error;
}
}
if(!qry.exec(QString("DELETE FROM ELEMENT WHERE CODE = '%1';").arg(ID)))
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
updateList();
error:
dApp->Enterprise().close();
}
void formElementList::on_buttonUpdate_released()
{
updateList();
}
void formElementList::on_tableView_doubleClicked(const QModelIndex &index)
{
openDocument(index);
}
void formElementList::openDocument(QModelIndex index)
{
QAbstractItemModel *model = ui->tableView->model();
//QModelIndex item = index;
formProduct *form = dApp->mainWindow()->createFormProduct();
//if (index.column() != 2)
// item = index.parent().child(index.row(), 2);
form->openDocument(model->index(index.row(), 2).data().toString());// item.data().toString());
form->show();
}
void formElementList::startDrag(const QModelIndex &index) {
if (!index.isValid())
return;
// Crear datos MIME
QMimeData *mimeData = new QMimeData();
QString data = mModel->data(index).toString();
mimeData->setText(data);
// Iniciar arrastre
QDrag *drag = new QDrag(ui->tableView);
drag->setMimeData(mimeData);
// Crear un ícono para el cursor
QPixmap pixmap(100, 30);
pixmap.fill(Qt::transparent); // Fondo transparente
QPainter painter(&pixmap);
painter.setBrush(Qt::yellow);
painter.drawRoundedRect(0, 0, pixmap.width(), pixmap.height(), 5, 5);
painter.setPen(Qt::black);
painter.drawText(pixmap.rect(), Qt::AlignCenter, data);
painter.end();
drag->setPixmap(pixmap); // Asignar el ícono al cursor
//drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2)); // Centro del ícono como punto caliente
drag->exec(Qt::MoveAction);
}
+40
View File
@@ -0,0 +1,40 @@
#ifndef FORMELEMENTLIST_H
#define FORMELEMENTLIST_H
#include <QWidget>
class QSqlQueryModel;
namespace Ui
{
class formElementList;
}
class formElementList : public QWidget
{
Q_OBJECT
public:
explicit formElementList(QWidget *parent = nullptr);
~formElementList();
private slots:
void on_buttonNew_released();
void on_buttonEdit_released();
void on_buttonClone_released();
void on_buttonDelete_released();
void on_buttonUpdate_released();
void on_tableView_doubleClicked(const QModelIndex &index);
void startDrag(const QModelIndex &index);
private:
Ui::formElementList *ui;
QSqlQueryModel *mModel;
void updateList();
void openDocument(QModelIndex index);
};
#endif // FORMELEMENTLIST_H
+126
View File
@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>formElementList</class>
<widget class="QWidget" name="formElementList">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>631</width>
<height>436</height>
</rect>
</property>
<property name="windowTitle">
<string>Elementos</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTableView" name="tableView">
<property name="selectionMode">
<enum>QAbstractItemView::MultiSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
</widget>
</item>
<item>
<widget class="QFrame" name="frame_2">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QPushButton" name="buttonNew">
<property name="text">
<string>Nuevo</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/add-file.svg</normaloff>:/resources/icons/add-file.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonEdit">
<property name="text">
<string>Editar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/pencil.svg</normaloff>:/resources/icons/pencil.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonClone">
<property name="text">
<string>Duplicar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/copy.svg</normaloff>:/resources/icons/copy.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonDelete">
<property name="text">
<string>Borrar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/recycle.svg</normaloff>:/resources/icons/recycle.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonUpdate">
<property name="text">
<string>Actualizar</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources>
<include location="../editabletreemodel.qrc"/>
</resources>
<connections/>
</ui>
+14
View File
@@ -0,0 +1,14 @@
#include "forminvoiceinlist.h"
#include "ui_forminvoiceinlist.h"
formInvoiceInList::formInvoiceInList(QWidget *parent) :
FormBaseList(parent),
ui(new Ui::formInvoiceInList)
{
//ui->setupUi(this);
}
formInvoiceInList::~formInvoiceInList()
{
delete ui;
}
+24
View File
@@ -0,0 +1,24 @@
#ifndef FORMINVOICEINLIST_H
#define FORMINVOICEINLIST_H
#include <QDockWidget>
#include "formbaselist.h"
namespace Ui {
class formInvoiceInList;
}
class formInvoiceInList : public FormBaseList
{
Q_OBJECT
public:
explicit formInvoiceInList(QWidget *parent = nullptr);
~formInvoiceInList();
private:
Ui::formInvoiceInList *ui;
};
#endif // FORMINVOICEINLIST_H
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>formInvoiceInList</class>
<widget class="QDockWidget" name="formInvoiceInList">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>596</width>
<height>320</height>
</rect>
</property>
<property name="windowTitle">
<string>DockWidget</string>
</property>
</widget>
<resources/>
<connections/>
</ui>
+509
View File
@@ -0,0 +1,509 @@
#include "formproduct.h"
#include "ui_formproduct.h"
#include "mapplication.h"
#include "treemodelcomposeelement.h"
#include "itemnumberdelegate.h"
#include "itemtextdelegate.h"
#include "itemtextpopupdelegate.h"
#include "itemcomboboxdelegate.h"
#include "QtSql"
formProduct::formProduct(QString aID, int aEditMode, QWidget *parent) :
formBase(aID, aEditMode, parent),
ui(new Ui::formProduct),
editMode(false)
{
ui->setupUi(this);
ui->editDischargeDate->setDate(QDate::currentDate());
ui->editUpdateDate->setDate(QDate::currentDate());
QStringList headers;
headers << tr("Código") //Código del elemento (editable)
<< tr("Título") //Título del elemento (NO editable)
<< tr("Cantidad") //Cantidad del elemento (editable)
<< tr("Cantidad total") //Cantidad total del elemento (NO editable)
<< tr("Unidad") //Unidad del elemento (editable)
<< tr("N. Precio Unitario") //Precio unitario del elemento (editable)
<< tr("N. Precio Total") //Precio total del elemento (NO editable)
<< tr("Tipo")
<< ("");
TreeModelComposeElement *model = new TreeModelComposeElement(headers, QByteArray());
ui->treeView->setModel(model);
// Texto con Popup
ItemTextPopupDelegate *LineTextPopup = new ItemTextPopupDelegate(this);
ui->treeView->setItemDelegateForColumn(0, LineTextPopup);
// Texto:
//ItemTextDelegate *LineTextEditor = new ItemTextDelegate(this);
//ui->treeView->setItemDelegateForColumn(0, LineTextEditor);
//ui->treeView->setItemDelegateForColumn(2, LineTextEditor);
// Números:
ItemNumberDelegate *doubleNumberEditor = new ItemNumberDelegate(0.0, 999999.99, 0.05, 2, this);
ui->treeView->setItemDelegateForColumn(2, doubleNumberEditor);
// Combobox:
//ItemComboboxDelegate *ComboboxEditor = new ItemComboboxDelegate(this);
//ui->treeView->setItemDelegateForColumn(6, ComboboxEditor);
connect(model, &TreeModelComposeElement::dataChanged, this, &formProduct::on_ModelSetData);
ui->treeView->setColumnWidth( 0, 150);
ui->treeView->setColumnWidth( 1, 250);
ui->treeView->setColumnWidth( 2, 80);
ui->treeView->setColumnWidth( 3, 80);
ui->treeView->setColumnWidth( 4, 50);
ui->treeView->setColumnWidth( 5, 80);
ui->treeView->setColumnWidth( 6, 80);
//Arg1: the number
//Arg2: how many 0 you want?
//Arg3: The base (10 - decimal, 16 hexadecimal - if you don't understand, choose 10)
// It seems like only decimal can support negative numbers.
ui->editCode->setText(QString("EL%1").arg(2, 10, 10, QChar('0')));
// Unidades:
dApp->Enterprise().open();
QSqlQueryModel *unitModel = new QSqlQueryModel(this);
unitModel->setQuery("SELECT * FROM UNIT", dApp->Enterprise());
//ui->comboUnit->setModel(unitModel);
QTableView* tableView = new QTableView( this );
QHeaderView* header = tableView->verticalHeader();
header->setDefaultSectionSize(20); // 20 px height
header->sectionResizeMode(QHeaderView::Fixed);
tableView->setModel( unitModel );
tableView->verticalHeader()->setVisible(false);
tableView->horizontalHeader()->setVisible(false);
tableView->setColumnWidth ( 0, 60 );
tableView->setColumnWidth ( 1, 160 );
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setAutoScroll(false);
ui->comboUnit->setModel( unitModel );
ui->comboUnit->setView( tableView );
ui->comboUnit->view()->setMinimumWidth(220);
dApp->Enterprise().close();
}
formProduct::~formProduct()
{
delete ui;
}
void formProduct::openDocument(QString id)
{
setEditMode();
ui->editCode->setText(id);
ui->editCode->setReadOnly(true);
ui->treeView->model()->removeRows(0, ui->treeView->model()->rowCount());
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
if(qry.exec(QString("SELECT * FROM ELEMENT WHERE CODE = '%1';").arg(id)))
{
qry.first();
ui->comboType1->setCurrentIndex(qry.value(qry.record().indexOf("TYPE1")).toInt());
ui->comboType2->setCurrentIndex(qry.value(qry.record().indexOf("TYPE2")).toInt());
ui->editTitle->setText(qry.value(qry.record().indexOf("TITLE")).toString());
ui->editDescription->setHtml(qry.value(qry.record().indexOf("DESCRIPTION")).toString());
//ui->editTitle->setText(qry.value(4).toString()); // FAMILY_ID
ui->comboUnit->setCurrentText(qry.value(qry.record().indexOf("UNIT_ID")).toString()); // UNIT_ID
ui->editUpdateDate->setDate(qry.value(qry.record().indexOf("DATE_UPDATE")).toDate());
//ui->editDischargeDate->setDate(qry.value().toDate());
ui->editPVP->setValue(qry.value(qry.record().indexOf("REAL_PRICE")).toDouble());
ui->editDiscount->setValue(qry.value(qry.record().indexOf("DISCOUNT")).toDouble());
ui->editPC->setValue(qry.value(qry.record().indexOf("PURCHASE_PRICE")).toDouble());
ui->editMargin->setValue(qry.value(qry.record().indexOf("BENEFIT")).toDouble());
ui->editPV->setValue(qry.value(qry.record().indexOf("SALE_PRICE")).toDouble());
ui->comboIVA->setCurrentText(qry.value(qry.record().indexOf("TAX")).toString());
ui->checkState->setChecked(qry.value(qry.record().indexOf("STATE")).toBool());
ui->editWeight->setValue(qry.value(qry.record().indexOf("WEIGHT")).toDouble());
ui->editHeight->setValue(qry.value(qry.record().indexOf("HEIGHT")).toDouble());
ui->editWidth->setValue(qry.value(qry.record().indexOf("WIDTH")).toDouble());
ui->editLength->setValue(qry.value(qry.record().indexOf("LENGHT")).toDouble());
if(qry.value(qry.record().indexOf("TYPE1")).toInt() == 0)
{
setComposeElement(true);
QList<QPair<QString, QString> > list;
if(qry.exec(QString("SELECT * FROM ELEMENTCOMPOSITION WHERE CODE = '%1';").arg(id)))
{
while(qry.next())
{
list.append(qMakePair(qry.value(qry.record().indexOf("ELEMENT_CODE")).toString(),
qry.value(qry.record().indexOf("ELEMENT_AMOUNT")).toString()));
}
int row = 0;
while(row < list.size())
{
ui->treeView->addRow();
QModelIndex index = ui->treeView->model()->index(row, 0);
setCellText(list.at(row).first, index, 0); // CODE
setCellText(list.at(row).second, index, 2); // AMOUNT
row ++;
}
ui->treeView->addRow();
}
else
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
}
else
{
setComposeElement(false);
}
}
else
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
dApp->Enterprise().close();
}
void formProduct::closeDocument()
{
close();
}
void formProduct::setEditMode()
{
editMode = true;
ui->editCode->setReadOnly(true);// ->setEnabled(false);
}
void formProduct::on_editPC_valueChanged(double arg1)
{
CalculatePrice();
}
void formProduct::on_editMargin_valueChanged(double arg1)
{
CalculatePrice();
}
void formProduct::on_editPV_valueChanged(double arg1)
{
}
void formProduct::on_editPV_editingFinished()
{
double pc = ui->editPC->value();
if (pc == 0)
return;
double ma;
double pv = ui->editPV->value();
ma = (pv/pc - 1) * 100;
if(ma != ui->editMargin->value())
ui->editMargin->setValue(ma);
}
void formProduct::on_comboIVA_currentIndexChanged(const QString &arg1)
{
CalculatePrice();
}
void formProduct::CalculatePrice()
{
double pc = ui->editPC->value();
double ma = ui->editMargin->value();
QString ivatext = ui->comboIVA->currentText().replace("%", "");
double iva = ivatext.toDouble();
double pv = pc * (1 + ma / 100);
ui->editPV->setValue(pv);
ui->editPVIVA->setValue( pv * (1 + iva / 100));
}
void formProduct::save()
{
// INSERT
QString Element;
QString ElementComp;
if(editMode == false)
{
Element = "INSERT INTO ELEMENT ("
"CODE, TYPE1, TYPE2, TITLE, DESCRIPTION, FAMILY_ID, UNIT_ID, "
"DATE_UPDATE, REAL_PRICE, DISCOUNT, PURCHASE_PRICE, BENEFIT, TAX, SALE_PRICE, "
"BARCODE, IMAGE, STATE, MANUFACTURER, GAMMA, "
"WEIGHT, HEIGHT, WIDTH, LENGHT"
") VALUES ("
":CODE, :TYPE1, :TYPE2, :TITLE, :DESCRIPTION, :FAMILY_ID, :UNIT_ID, "
":DATE_UPDATE, :REAL_PRICE, :DISCOUNT, :PURCHASE_PRICE, :BENEFIT, :TAX, :SALE_PRICE, "
":BARCODE, :IMAGE, :STATE, :MANUFACTURER, :GAMMA, "
":WEIGHT, :HEIGHT, :WIDTH, :LENGHT"
");";
ElementComp = "INSERT INTO ELEMENTCOMPOSITION ("
"CODE, ELEMENT_CODE, ELEMENT_AMOUNT"
") VALUES ("
":CODE, :ELEMENT_CODE, :ELEMENT_AMOUNT"
");";
}
// UPDATE
else
{
Element = "UPDATE ELEMENT SET "
"TYPE1 = :TYPE1, TYPE2 = :TYPE2, TITLE = :TITLE, DESCRIPTION = :DESCRIPTION, FAMILY_ID = :FAMILY_ID, "
"UNIT_ID = :UNIT_ID, DATE_UPDATE = :DATE_UPDATE, REAL_PRICE = :REAL_PRICE, DISCOUNT = :DISCOUNT, "
"PURCHASE_PRICE = :PURCHASE_PRICE, BENEFIT = :BENEFIT, TAX = :TAX, SALE_PRICE = :SALE_PRICE, BARCODE = :BARCODE, IMAGE = :IMAGE, "
"STATE = :STATE, MANUFACTURER = :MANUFACTURER, GAMMA = :GAMMA, WEIGHT = :WEIGHT, HEIGHT = :HEIGHT, "
"WIDTH = :WIDTH, LENGHT = :LENGHT "
"WHERE CODE = :CODE"
";";
ElementComp = "UPDATE ELEMENTCOMPOSITION SET "
"ELEMENT_AMOUNT = :ELEMENT_AMOUNT "
"WHERE CODE = :CODE AND ELEMENT_CODE = :ELEMENT_CODE";
}
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
// 1. Si es compuesto crear la lista de elementos que lo componen:
if(ui->comboType1->currentIndex() == 0)
{
QAbstractItemModel *model = ui->treeView->model();
for (int i = 0; i < model->rowCount(); i++)
{
// Obtiene los datos de la primera columna
QString elementCode = model->index(i, 0).data().toString();
// Verifica si los datos son válidos
if (elementCode.isEmpty())
continue;
qry.prepare(ElementComp);
qry.bindValue(":CODE", ui->editCode->text());
qry.bindValue(":ELEMENT_CODE", elementCode);
qry.bindValue(":ELEMENT_AMOUNT", model->index(i, 2).data().toDouble());
if(!qry.exec())
{
// barrar lo creado: eliminar las composiciones ya insertadas para este producto
if (!insertedElementCodes.isEmpty())
{
QSqlQuery qryDel = QSqlQuery(dApp->Enterprise());
qryDel.prepare(QString("DELETE FROM ELEMENTCOMPOSITION WHERE CODE = :CODE AND ELEMENT_CODE IN (%1)").arg(QString(insertedElementCodes.size(), '?').replace('?', ":ELEMENT_CODE")));
qryDel.bindValue(":CODE", ui->editCode->text());
for (int j = 0; j < insertedElementCodes.size(); ++j)
{
qryDel.bindValue(QString(":ELEMENT_CODE%1").arg(j), insertedElementCodes.at(j));
}
qryDel.exec();
}
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
dApp->Enterprise().close();
return;
}}
}
}
// 2. Crear el elemento principal
qry.prepare(Element);
qry.bindValue(":CODE", ui->editCode->text());
qry.bindValue(":TYPE1", ui->comboType1->currentIndex());
qry.bindValue(":TYPE2", ui->comboType2->currentIndex());
qry.bindValue(":TITLE", ui->editTitle->text());
qry.bindValue(":DESCRIPTION", ui->editDescription->toHtml());
//qry.bindValue(":FAMILY_ID", ui->editCode->text());
qry.bindValue(":UNIT_ID", ui->comboUnit->currentText());
qry.bindValue(":DATE_UPDATE", ui->editUpdateDate->date());
qry.bindValue(":REAL_PRICE", ui->editPVP->value());
qry.bindValue(":DISCOUNT", ui->editDiscount->value());
qry.bindValue(":PURCHASE_PRICE", ui->editPC->value());
qry.bindValue(":BENEFIT", ui->editMargin->value());
qry.bindValue(":TAX", ui->comboIVA->currentText().replace("%", ""));
qry.bindValue(":SALE_PRICE", ui->editPV->text());
//qry.bindValue(":BARCODE", ui->edit->text());
//qry.bindValue(":IMAGE", ui->editCode->text());
qry.bindValue(":STATE", ui->checkState->isChecked());
//qry.bindValue(":MANUFACTURER", ui->editCode->text());
//qry.bindValue(":GAMMA", ui->editCode->text());
qry.bindValue(":WEIGHT", ui->editWeight->text());
qry.bindValue(":HEIGHT", ui->editHeight->text());
qry.bindValue(":WIDTH", ui->editWidth->text());
qry.bindValue(":LENGHT", ui->editLength->text());
if(!qry.exec())
{
//goto error;
}
setWindowTitle(mDocumentID);
QTabWidget * prt = static_cast<QTabWidget*>(parent()->parent());
prt->setTabText(prt->currentIndex(), ui->editCode->text() + " - " + ui->editTitle->text());
dApp->Enterprise().close();
setEditMode();
return;
error:
dApp->Enterprise().close();
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
void formProduct::on_buttonSave_released()
{
// Salvar
save();
}
void formProduct::on_editPVIVA_valueChanged(const QString &arg1)
{
ui->editUpdateDate->setDate(QDate::currentDate());
}
void formProduct::on_ModelSetData(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
Q_UNUSED(bottomRight);
if(topLeft.column() == 0)
{
InsertElement(topLeft.data(roles.first()).toString(), topLeft);
}
else if(topLeft.column() == 2)
{
QAbstractItemModel /*TreeModelComposeElement*/ *aModel = ui->treeView->model();
double pt = 0;
for(int i = 0; i < aModel->rowCount(); i++)
{
QModelIndex idx = aModel->index(i, 6);
pt += idx.data().toDouble();
}
ui->editPC->setValue(pt);
}
}
void formProduct::setLineType(QString type, QModelIndex index)
{
setCellText(type, index, 7);
}
void formProduct::setCellText(QString val, QModelIndex index, int col)
{
//QModelIndex selindex = ui->treeView->selectionModel()->currentIndex();
QAbstractItemModel *treemodel = ui->treeView->model();
QModelIndex child = treemodel->index(index.row(), col, index.parent().isValid() ? index.parent() : QModelIndex());
treemodel->setData(child, QVariant(val), Qt::EditRole);
}
bool formProduct::InsertElement(QString ID, QModelIndex index)
{
if (ID.isEmpty())
return false;
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
if (qry.exec(QString("SELECT * FROM ELEMENT WHERE CODE = '%1';").arg(ID)))
{
qry.first();
setCellText(qry.value(qry.record().indexOf("TITLE")).toString(), index, 1); // TITLE
setCellText(qry.value(qry.record().indexOf("UNIT_ID")).toString(), index, 4); // UNIT ----QSqlQuery::value: not positioned on a valid record
/*
if (qry.value(qry.record().indexOf("TYPE")).toInt() == 0)
{
on_buttonInsertChild_released();
QSqlQuery comp = QSqlQuery(dApp->Enterprise());
if (comp.exec(QString("SELECT * FROM ELEMENTCOMPOSITION WHERE CODE = '%1';").arg(ID)))
{
while (comp.next())
{
on_buttonInsertRow_released();
InsertElement(comp.value(1).toString());
setCellText(4, comp.value(comp.record().indexOf("ELEMENT_AMOUNT")).toString()); //AMOUNT
}
}
}
else*/
{
setCellText(qry.value(qry.record().indexOf("PURCHASE_PRICE")).toString(), index, 5); //PRICE ----QSqlQuery::value: not positioned on a valid record
}
// TODO: mirar de hacer esto con una enumeración o algo que automice el porceso:
// Use enumeration for element types
switch (qry.value(qry.record().indexOf("TYPE1")).toInt())
{
case ElementType::Composed:
setLineType("CO", index); // type
break;
case ElementType::Material:
setLineType("MT", index); // type
break;
case ElementType::ManPower:
setLineType("MO", index); // type
break;
case ElementType::Machinery:
setLineType("MQ", index); // type
break;
case ElementType::Subcontracted:
setLineType("SC", index); // type
break;
case ElementType::Other:
setLineType("OT", index); // type
break;
default:
setLineType("UNKNOWN", index); // type
break;
}
}
else
{
qDebug() << qry.lastError().text();
}
dApp->Enterprise().close();
return false;
}
void formProduct::on_comboType2_currentIndexChanged(int index)
{
if(index == 0)
setComposeElement(true);
else
setComposeElement(false);
}
void formProduct::setComposeElement(bool val)
{
ui->editPVP->setEnabled(!val);
ui->editDiscount->setEnabled(!val);
ui->editPC->setReadOnly(val);
ui->groupBox_6->setVisible(!val);
//ui->tabCompose->setVisible(val);
ui->comboType1->setEnabled(!val);
//ui->comboType2->setEnabled(!val);
}
+55
View File
@@ -0,0 +1,55 @@
#ifndef FORMPRODUCT_H
#define FORMPRODUCT_H
#include <QWidget>
#include "formbase.h"
#include "../src/elementtype.h"
namespace Ui
{
class formProduct;
}
class formProduct : public formBase
{
Q_OBJECT
public:
//explicit formProduct(QWidget *parent = 0);
explicit formProduct(QString aID = "", int aEditMode = 0, QWidget *parent = nullptr);
~formProduct();
void newDocument() override {}
void openDocument(QString id) override;
void closeDocument() override;
void save() override;
bool needsave() override { return mNeedSave; }
void setEditMode(bool aMode) override {}
public slots:
void on_ModelSetData(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles);
private slots:
void on_editPC_valueChanged(double arg1);
void on_editMargin_valueChanged(double arg1);
void on_editPV_valueChanged(double arg1);
void on_comboIVA_currentIndexChanged(const QString &arg1);
void on_editPV_editingFinished();
void on_buttonSave_released();
void on_editPVIVA_valueChanged(const QString &arg1);
void on_comboType2_currentIndexChanged(int index);
private:
Ui::formProduct *ui;
bool editMode;
void CalculatePrice();
bool InsertElement(QString ID, QModelIndex index);
void setLineType(QString type, QModelIndex index);
void setCellText(QString val, QModelIndex index, int col);
void setEditMode();
void setComposeElement(bool val);
};
#endif // FORMPRODUCT_H
File diff suppressed because it is too large Load Diff
+249
View File
@@ -0,0 +1,249 @@
#include "formthird.h"
#include "ui_formthird.h"
#include "mapplication.h"
#include "formbase.h"
#include <QFileDialog>
#include <QtSql>
formThird::formThird(QString aID, int aEditMode, QWidget *parent) :
formBase(aID, aEditMode, parent),
ui(new Ui::formThird),
rowid(-1)
{
ui->setupUi(this);
ui->tabClient->setVisible(false);
ui->tabSupplier->setVisible(false);
ui->editDischargeDate->setDate(QDate::currentDate());
ui->editUpdateDate->setDate(QDate::currentDate());
connect(ui->Logo, &AvatarWidget::addClicked, this, &formThird::LoadLogo);
//connect(ui->Logo, &AvatarWidget::clicked, this, &formThird::LoadLogo);
mEditMode = false;
}
formThird::~formThird()
{
delete ui;
}
void formThird::openDocument(QString id)
{
mEditMode = true;
//ui->editCode->setText(id);
//ui->editCode->setReadOnly(true);
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
QString command = QString("SELECT * FROM THIRD WHERE ID = '%1';").arg(id);
if (qry.exec(command))
{
qry.first();
ui->editName->setText(qry.value(qry.record().indexOf("NAME")).toString());
ui->editNickname->setText(qry.value(qry.record().indexOf("NICKNAME")).toString());
ui->editCIF->setText(qry.value(qry.record().indexOf("CIF")).toString());
ui->editIntraCode->setText(qry.value(qry.record().indexOf("INTRA_FC")).toString());
ui->comboState->setCurrentIndex(qry.value(qry.record().indexOf("STATE")).toInt());
ui->comboClient->setCurrentIndex(qry.value(qry.record().indexOf("CLIENT_STATE")).toInt());
ui->comboClient->setCurrentIndex(qry.value(qry.record().indexOf("SUPPLIER_STATE")).toInt());
ui->editClientCode->setText(qry.value(qry.record().indexOf("CLIENT_CODE")).toString());
ui->editSupplierCode->setText(qry.value(qry.record().indexOf("SUPPLIER_CODE")).toString());
ui->editAddress->setPlainText(qry.value(qry.record().indexOf("ADDRESS")).toString());
ui->editCP->setText(qry.value(qry.record().indexOf("POSTCODE")).toString());
ui->editCity->setText(qry.value(qry.record().indexOf("CITY")).toString());
ui->editProvince->setText(qry.value(qry.record().indexOf("PROVINCE")).toString());
ui->comboCountry->setCurrentText(qry.value(qry.record().indexOf("COUNTRY_ID")).toString());
ui->editPhone->setText(qry.value(qry.record().indexOf("PHONE")).toString());
ui->editFax->setText(qry.value(qry.record().indexOf("FAX")).toString());
ui->editMobile->setText(qry.value(qry.record().indexOf("MOBILE")).toString());
ui->editEmail->setText(qry.value(qry.record().indexOf("EMAIL")).toString());
ui->editWebside->setText(qry.value(qry.record().indexOf("WEBSIDE")).toString());
ui->editPublicNotes->setHtml(qry.value(qry.record().indexOf("NOTE_PUBLIC")).toString());
ui->editPrivateNotes->setHtml(qry.value(qry.record().indexOf("NOTE_PRIVATE")).toString());
ui->editDischargeDate->setDate(qry.value(qry.record().indexOf("CREATEDAT")).toDate());
ui->editUpdateDate->setDate(qry.value(qry.record().indexOf("UPDATEDAT")).toDate());
}
else
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
dApp->Enterprise().close();
}
void formThird::closeDocument()
{
close();
qDebug() << " Terceros: closeDocument";
}
void formThird::on_cbClient_currentIndexChanged(int index)
{
if(index == 0)
ui->tabClient->setVisible(false);
else
ui->tabClient->setVisible(true);
}
void formThird::on_cbSupplier_currentIndexChanged(int index)
{
if(index == 0)
ui->tabSupplier->setVisible(false);
else
ui->tabSupplier->setVisible(true);
}
void formThird::on_buttonSave_released()
{
save();
}
void formThird::LoadLogo()
{
QString imageFile = QFileDialog::getOpenFileName(this,
tr("Elige una imagen"),
"",
tr("Todas las imagenes(*.png *.jpg *.gif *.bmp)"));
/*
if(imageFile.isEmpty())
return;
imageProfile = ImageCropperDialog::getCroppedImage(imageFile, 600, 400, CropperShape::SQUARE);
if (imageProfile.isNull())
return;
ui->profilePicture->setAvatarPixmap(imageProfile);
*/
ui->Logo->setAvatarPath(imageFile);
}
void formThird::save()
{
QString command;
if (mEditMode)
command = "UPDATE THIRD SET "
"FORM = :FORM, CIF = :CIF, NAME = :NAME, NICKNAME = :NICKNAME, FAMILY = :FAMILY, "
"INTRA_FC = :INTRA_FC, STATE = :STATE, CLIENT_STATE = :CLIENT_STATE, CLIENT_CODE = :CLIENT_CODE, "
"CLIENT_ACCOUNT = :CLIENT_ACCOUNT, SUPPLIER_STATE = :SUPPLIER_STATE, SUPPLIER_CODE = :SUPLLIR_CODE, "
"SUPPLIER_ACCOUNT = :SUPPLIER_ACCOUNT, ADDRESS = :ADDRESS, POSTCODE = :POSTCODE, CITY = :CITY, "
"PROVINCE = :PROVINCE, COUNTRY_ID = :COUNTRY_ID, PHONE = :PHONE, FAX = :FAX, "
"EMAIL = :EMAIL, WEBSIDE = :WEBSIDE, PAYMENT_METHOD = :PAYMENT_METHOD, PAYMENT_TYPE = :PAYMENT_TYPE, "
"LOGO = :LOGO, NOTE_PUBLIC = :NOTE_PUBLIC, NOTE_PRIVATE = :NOTE_PRIVATE, UPDATEDAT = :UPDATEDAT, "
"CREATEDAT = :CREATEDAT, CREATEDBY = :CREATEBY "
"WHERE CIF = '" + ui->editCIF->text() +
"';";
else
command = "INSERT INTO THIRD ("
"FORM, CIF, NAME, NICKNAME, FAMILY, INTRA_FC, STATE, CLIENT_STATE, CLIENT_CODE, "
"CLIENT_ACCOUNT, SUPPLIER_STATE, SUPPLIER_CODE, SUPPLIER_ACCOUNT, ADDRESS, "
"POSTCODE, CITY, PROVINCE, COUNTRY_ID, PHONE, FAX, EMAIL, WEBSIDE, "
"PAYMENT_METHOD, PAYMENT_TYPE, LOGO, NOTE_PUBLIC, NOTE_PRIVATE, UPDATEDAT, "
"CREATEDAT, CREATEDBY"
") VALUES ("
":FORM, :CIF, :NAME, :NICKNAME, :FAMILY, :INTRA_FC, :STATE, :CLIENT_STATE, :CLIENT_CODE, "
":CLIENT_ACCOUNT, :SUPPLIER_STATE, :SUPPLIER_CODE, :SUPPLIER_ACCOUNT, :ADDRESS, "
":POSTCODE, :CITY, :PROVINCE, :COUNTRY_ID, :PHONE, :FAX, :EMAIL, :WEBSIDE, "
":PAYMENT_METHOD, :PAYMENT_TYPE, :LOGO, :NOTE_PUBLIC, :NOTE_PRIVATE, :UPDATEDAT, "
":CREATEDAT, :CREATEDBY"
");";
qDebug() << command;
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
qry.prepare(command);
//qry.bindValue(":FORM", );
qry.bindValue(":CIF", ui->editCIF->text());
qry.bindValue(":NAME", ui->editName->text());
qry.bindValue(":NICKNAME", ui->editNickname->text());
//qry.bindValue(":FAMILY", );
qry.bindValue(":INTRA_FC", ui->editIntraCode->text());
qry.bindValue(":STATE", ui->comboState->currentIndex());
qry.bindValue(":CLIENT_STATE", ui->comboClient->currentIndex());
qry.bindValue(":CLIENT_CODE", ui->editClientCode->text());
qry.bindValue(":CLIENT_ACCOUNT", ui->editAccountClient->text());
qry.bindValue(":SUPPLIER_STATE", ui->comboSupplier->currentIndex());
qry.bindValue(":SUPPLIER_CODE", ui->editSupplierCode->text());
qry.bindValue(":SUPPLIER_ACCOUNT", ui->editAccountSupplier->text());
qry.bindValue(":ADDRESS", ui->editAddress->toPlainText());
qry.bindValue(":POSTCODE", ui->editCP->text());
qry.bindValue(":CITY", ui->editCity->text());
qry.bindValue(":PROVINCE", ui->editProvince->text());
qry.bindValue(":COUNTRY_ID", ui->comboCountry->currentText());
//qry.bindValue(":COUNTRY", ui->editIntraCode->text());
qry.bindValue(":PHONE", ui->editPhone->text());
qry.bindValue(":FAX", ui->editFax->text());
qry.bindValue(":MOBILE", ui->editMobile->text());
qry.bindValue(":EMAIL", ui->editEmail->text());
qry.bindValue(":WEBSIDE", ui->editWebside->text());
//qry.bindValue(":PAYMENT_METHOD", ui->editPhone->text());
//qry.bindValue(":PAYMENT_TYPE", ui->editFax->text());
//qry.bindValue(":LOGO", ui->editMobile->text());
qry.bindValue(":NOTE_PUBLIC", ui->editPublicNotes->toHtml());
qry.bindValue(":NOTE_PRIVATE", ui->editPrivateNotes->toHtml());
qry.bindValue(":UPDATEDAT", ui->editUpdateDate->date());
qry.bindValue(":CREATEDAT", ui->editDischargeDate->date());
//qry.bindValue(":CREATEDBY", ui->editWebside->text());
if (!qry.exec())
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
else
{
setEditMode();
}
dApp->Enterprise().close();
}
void formThird::setEditMode()
{
mEditMode = true;
ui->editDischargeDate->setReadOnly(true);
}
void formThird::on_editName_textChanged(const QString &arg1)
{
mNeedSave = true;
}
void formThird::on_comboClient_currentIndexChanged(int index)
{
/*
// Ocultar pestaña
int indexToHide = 2;
QWidget *tab = ui->tabWidget->widget(indexToHide);
hiddenTabs[indexToHide] = tab; // Guarda la pestaña en un mapa
ui->tabWidget->removeTab(indexToHide);
// Mostrar pestaña
int indexToShow = 2;
if (hiddenTabs.contains(indexToShow)) {
ui->tabWidget->insertTab(indexToShow, hiddenTabs[indexToShow]);
hiddenTabs.remove(indexToShow);
}
*/
}
+46
View File
@@ -0,0 +1,46 @@
#ifndef FORMTHIRD_H
#define FORMTHIRD_H
#include <QWidget>
#include "formbase.h"
namespace Ui {
class formThird;
}
class formThird : public formBase
{
Q_OBJECT
public:
//explicit formThird(QWidget *parent = 0);
explicit formThird(QString aID = "", int aEditMode = 0, QWidget *parent = nullptr);
~formThird();
void newDocument() override {}
void openDocument(QString id) override;
void closeDocument() override;
void save() override;
bool needsave() override { return mNeedSave; }
void setEditMode(bool aMode) override {}
private slots:
void on_cbClient_currentIndexChanged(int index);
void on_cbSupplier_currentIndexChanged(int index);
void on_buttonSave_released();
void on_editName_textChanged(const QString &arg1);
void on_comboClient_currentIndexChanged(int index);
private:
Ui::formThird *ui;
int rowid;
QMap<int, QWidget*> hiddenTabs;
void LoadLogo();
void setEditMode();
};
#endif // FORMTHIRD_H
File diff suppressed because it is too large Load Diff
+157
View File
@@ -0,0 +1,157 @@
#include "formthirdlist.h"
#include "ui_formthirdlist.h"
#include "mapplication.h"
#include "mainwindow.h"
#include "formthird.h"
#include "utils/filtertableheader.h"
#include <QSqlQueryModel>
#include <QResizeEvent>
formThirdList::formThirdList(QWidget *parent) :
QWidget(parent),
ui(new Ui::formThirdList)
{
ui->setupUi(this);
//QStringList header;
//header << tr("Código") << tr("Título") << tr("Tipo") << tr("Precio de Compra");
mModel = new QSqlQueryModel(this);
//ui->tableView->setModel(mModel);
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(mModel);
ui->tableView->setModel(proxyModel);
// Set up filter row
m_tableHeader = new FilterTableHeader(ui->tableView);
ui->tableView->setHorizontalHeader(m_tableHeader);
m_tableHeader->setFilter(1, "");
m_tableHeader->setFocusColumn(1);
// Disconnect clicking in header to select column, since we will use it for sorting.
// Note that, in order to work, this cannot be converted to the standard C++11 format.
disconnect(m_tableHeader, SIGNAL(sectionPressed(int)),this, SLOT(selectColumn(int)));
//connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::filterChanged, filterHeader(), &FilterTableHeader::filterChanged);
connect(m_tableHeader, &FilterTableHeader::filterChanged, this, &formThirdList::applyFilter);
updateList();
ui->tableView->setColumnHidden(0, true);
m_tableHeader->generateFilters(mModel->columnCount(), 0);
}
formThirdList::~formThirdList()
{
delete ui;
}
void formThirdList::updateList()
{
dApp->Enterprise().open();
mModel->setQuery("SELECT ID, CIF, NAME, NICKNAME, ADDRESS, CITY, PHONE, MOBILE, FAX, EMAIL FROM THIRD ORDER BY ID ASC",
dApp->Enterprise());
dApp->Enterprise().close();
}
void formThirdList::applyFilter()
{
dApp->Enterprise().open();
QString query = "SELECT ID, CIF, NAME, NICKNAME, ADDRESS, CITY, PHONE, MOBILE, FAX, EMAIL FROM THIRD";
QString filters = "";
for (int i = 1; i < mModel->columnCount(); i++)
{
if(m_tableHeader->filterValue(i).isEmpty())
continue;
if(!filters.isEmpty())
filters += " AND ";
//WHERE NAME LIKE '%ter%'
filters += mModel->headerData(i, Qt::Horizontal).toString() + " LIKE '%" + m_tableHeader->filterValue(i) + "%'";
}
if (!filters.isEmpty())
query += " WHERE " + filters;
//query += " ORDER BY ID ASC";
mModel->setQuery(query,
dApp->Enterprise());
if (mModel->lastError().isValid())
qDebug() << mModel->lastError();
dApp->Enterprise().close();
}
void formThirdList::on_buttonNew_released()
{
formThird *form = dApp->mainWindow()->createFormThird();
form->show();
}
void formThirdList::on_buttonEdit_released()
{
openDocument(ui->tableView->currentIndex());
}
void formThirdList::on_buttonClone_released()
{
}
void formThirdList::on_buttonDelete_released()
{
QModelIndex index = ui->tableView->currentIndex();
QAbstractItemModel *model = const_cast<QAbstractItemModel*>(index.model()); // Obtén el modelo asociado
QModelIndex parentIndex = index.parent(); // Obtén el índice del padre
if (index.column() != 0)
index = model->index(index.row(), 0, parentIndex); // Obtén el índice del hijo
QString ID = index.data().toString();
QModelIndex childIndex = model->index(index.row(), 2, parentIndex); // Obtén el índice del hijo
int type = childIndex.data().toInt(); // Accede al dato
dApp->Enterprise().open();
QSqlQuery qry = QSqlQuery(dApp->Enterprise());
if(!qry.exec(QString("DELETE FROM THIRD WHERE CODE = '%1';").arg(ID)))
{
qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
}
updateList();
dApp->Enterprise().close();
}
void formThirdList::on_buttonUpdate_released()
{
updateList();
}
void formThirdList::on_tableView_doubleClicked(const QModelIndex &index)
{
openDocument(index);
}
void formThirdList::openDocument(QModelIndex index)
{
formThird *form = dApp->mainWindow()->createFormThird();
form->openDocument(index.model()->index(index.row(), 0).data().toString());
form->show();
}
void formThirdList::resizeEvent(QResizeEvent *event)
{
QStringList texts = { tr("Nuevo"), tr("Editar"), tr("Clonar"), tr("Borrar"), tr("Actualizar") };
QList<QPushButton*> buttons = { ui->buttonNew, ui->buttonEdit, ui->buttonClone, ui->buttonDelete, ui->buttonUpdate };
for (int i = 0; i < buttons.size(); ++i) {
buttons[i]->setText(event->size().width() > 390 ? texts[i] : "");
}
}
+45
View File
@@ -0,0 +1,45 @@
#ifndef FORMTHIRDLIST_H
#define FORMTHIRDLIST_H
#include <QWidget>
class QSqlQueryModel;
class FilterTableHeader;
namespace Ui
{
class formThirdList;
}
class formThirdList : public QWidget
{
Q_OBJECT
public:
explicit formThirdList(QWidget *parent = 0);
~formThirdList();
private slots:
void on_buttonNew_released();
void on_buttonEdit_released();
void on_buttonClone_released();
void on_buttonDelete_released();
void on_buttonUpdate_released();
void on_tableView_doubleClicked(const QModelIndex &index);
private:
Ui::formThirdList *ui;
QSqlQueryModel *mModel;
FilterTableHeader *m_tableHeader;
void updateList();
void openDocument(QModelIndex index);
void applyFilter();
protected:
void resizeEvent(QResizeEvent *event) override;
};
#endif // FORMTHIRDLIST_H
+130
View File
@@ -0,0 +1,130 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>formThirdList</class>
<widget class="QWidget" name="formThirdList">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>285</height>
</rect>
</property>
<property name="windowTitle">
<string>Terceros</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTableView" name="tableView">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QFrame" name="frame_2">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QPushButton" name="buttonNew">
<property name="text">
<string>Nuevo</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/add-file.svg</normaloff>:/resources/icons/add-file.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonEdit">
<property name="text">
<string>Editar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/pencil.svg</normaloff>:/resources/icons/pencil.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonClone">
<property name="text">
<string>Duplicar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/copy.svg</normaloff>:/resources/icons/copy.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonDelete">
<property name="text">
<string>Borrar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/delete.svg</normaloff>:/resources/icons/delete.svg</iconset>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonUpdate">
<property name="text">
<string>Actualizar</string>
</property>
<property name="icon">
<iconset resource="../editabletreemodel.qrc">
<normaloff>:/resources/icons/recycle.svg</normaloff>:/resources/icons/recycle.svg</iconset>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources>
<include location="../editabletreemodel.qrc"/>
</resources>
<connections/>
</ui>
+304
View File
@@ -0,0 +1,304 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include "mapplication.h"
#include "treemodel.h"
#include "formbudget.h"
#include "formthird.h"
#include "formproduct.h"
#include "formelementlist.h"
#include "formthirdlist.h"
#include "forminvoiceinlist.h"
#include "formbudgetlist.h"
//#include "QsfMainWindow.h"
#include "QMainWindow"
#include "QTabWidget"
#include "QMessageBox"
#if !SARIBBON_USE_3RDPARTY_FRAMELESSHELPER
#include "gui/SARibbon/src/SARibbonBar/SAFramelessHelper.h"
#endif
#include "gui/SARibbon/src/SARibbonBar/SARibbonApplicationButton.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonBar.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonButtonGroupWidget.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCategory.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCheckBox.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonColorToolButton.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonComboBox.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCustomizeDialog.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonCustomizeWidget.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonGallery.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonLineEdit.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonMenu.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonPannel.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonQuickAccessBar.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonToolButton.h"
#include "gui/SARibbon/src/SARibbonBar/colorWidgets/SAColorGridWidget.h"
#include "gui/SARibbon/src/SARibbonBar/colorWidgets/SAColorPaletteGridWidget.h"
#include "gui/SARibbon/src/SARibbonBar/SARibbonSystemButtonBar.h"
#include <QTextEdit>
#include <QFile>
#include <QDockWidget>
MainWindow::MainWindow(QWidget *parent)
: SARibbonMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this); //<<----------- pensar en esto
//允许嵌套dock
setDockNestingEnabled(true);
setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
m_workspace = new QTabWidget;
setCentralWidget(m_workspace);
m_workspace->setTabsClosable(true);
connect(m_workspace, &QTabWidget::tabCloseRequested, this, &MainWindow::tabCloseRequested);
QStatusBar* statusBar = new QStatusBar();
statusBar->setObjectName("QsfStatuBar");
this->setStatusBar(statusBar);
this->setStatusTip("Prueba: javier braña");
this->setRibbonTheme(SARibbonTheme::RibbonThemeOffice2021Blue);
SARibbonBar* ribbon = ribbonBar();
ribbon->setContentsMargins(2, 0, 2, 0);
QAbstractButton* btn = ribbon->applicationButton();
if (!btn) {
//! cn: SARibbonBar默认就会创建一个SARibbonApplicationButton,因此,在正常情况下,这个位置不会进入
//! en: SARibbonBar creates a SARibbonApplicationButton by default. Therefore, under normal circumstances, this location will not enter
btn = new SARibbonApplicationButton(this);
ribbon->setApplicationButton(btn);
}
ribbon->applicationButton()->setText((" &File "));
SARibbonCategory* categoryThirdParties = new SARibbonCategory();
categoryThirdParties->setCategoryName(tr("Tercero"));
categoryThirdParties->setObjectName(("categoryThirdParties"));
ribbon->addCategoryPage(categoryThirdParties);
SARibbonPannel* pannel1 = new SARibbonPannel(tr("pannel one"));
pannel1->setObjectName("categoryThirdParties-pannel1");
categoryThirdParties->addPannel(pannel1);
QAction* actSave = createAction(tr("Save"), ":/resources/icons/save.svg");
connect(actSave, &QAction::triggered, this, [ this ](bool b) {
Q_UNUSED(b);
this->createFormBudget();
});
pannel1->addLargeAction(actSave);
SARibbonButtonGroupWidget* btnGroup1 = new SARibbonButtonGroupWidget(pannel1);
btnGroup1->setObjectName("SARibbonButtonGroupWidget1");
btnGroup1->setWindowTitle("SARibbonButtonGroupWidget1");
btnGroup1->addAction(createAction(tr("Decrease Margin"), ":/resources/icons/brush.png"));
btnGroup1->addAction(createAction(tr("Decrease Indent"), ":/resources/icons/add-file.svg"));
btnGroup1->addAction(createAction(tr("Wrap Image Left"), ":/resources/icons/tag.svg"));
btnGroup1->addAction(createAction(tr("Wrap Image Right"),":/resources/icons/recycle.svg"));
pannel1->addWidget(btnGroup1, SARibbonPannelItem::Medium);
SARibbonButtonGroupWidget* btnGroup2 = new SARibbonButtonGroupWidget(pannel1);
btnGroup2->setObjectName("SARibbonButtonGroupWidget2");
btnGroup2->setWindowTitle("SARibbonButtonGroupWidget2");
btnGroup2->addAction(createAction(tr("Decrease Margin"), ":/resources/icons/brush.png"));
btnGroup2->addAction(createAction(tr("Decrease Indent"), ":/resources/icons/add-file.svg"));
btnGroup2->addAction(createAction(tr("Wrap Image Left"), ":/resources/icons/tag.svg"));
btnGroup2->addAction(createAction(tr("Wrap Image Right"),":/resources/icons/recycle.svg"));
pannel1->addWidget(btnGroup2, SARibbonPannelItem::Medium);
SARibbonCategory* categoryDelete = new SARibbonCategory();
categoryDelete->setCategoryName(("Delete"));
categoryDelete->setObjectName(("categoryDelete"));
ribbon->addCategoryPage(categoryDelete);
}
QDockWidget* MainWindow::createDockWidget( QString title, QString name, Qt::DockWidgetArea area )
{
QDockWidget* tDock = new QDockWidget(title);
tDock->setObjectName("dockWidget");
tDock->setFloating(true);
QWidget* docWid1 = new QWidget;
docWid1->setObjectName("dockWidgetContents");
tDock->setWidget(docWid1);
return tDock;
}
QWidget* MainWindow::createWorkWidget( QString title, QString name )
{
QWidget* tWidget = new QWidget();
tWidget->setWindowTitle(title);
m_workspace->addTab(tWidget, title);
return tWidget;
}
void MainWindow::addWorkWidget(QWidget *tWidget, QString title)
{
m_workspace->addTab(tWidget, (title == "") ? tWidget->windowTitle() : title);
m_workspace->setCurrentIndex(m_workspace->count() - 1);
}
void MainWindow::setCompany(QString ID)
{
setWindowTitle(ID);
auto *form3 = new formElementList();
QDockWidget *a = createDockWidget(form3->windowTitle(), form3->windowTitle(), Qt::LeftDockWidgetArea);
a->setWidget(form3);
addDockWidget(Qt::LeftDockWidgetArea, a);
auto *form4 = new formThirdList();
QDockWidget *b = createDockWidget(form4->windowTitle(), form4->windowTitle(), Qt::LeftDockWidgetArea);
b->setWidget(form4);
//addDockWidget(Qt::LeftDockWidgetArea, a);
tabifyDockWidget(a, b);
/*
auto *form5 = new formInvoiceInList();
a = createDockWidget(form5->windowTitle(), form5->windowTitle(), Qt::LeftDockWidgetArea);
a->setWidget(form5);
addDockWidget(Qt::LeftDockWidgetArea, a);*/
auto *form6 = new FormBudgetList();
QDockWidget *c = createDockWidget(form6->windowTitle(), form6->windowTitle(), Qt::RightDockWidgetArea);
c->setWidget(form6);
addDockWidget(Qt::RightDockWidgetArea, c);
}
formProduct * MainWindow::createFormProduct()
{
auto *form = new formProduct();
form->setWindowTitle("Nuevo Elemento");
addWorkWidget(form, form->windowTitle());
return form;
}
formThird * MainWindow::createFormThird()
{
auto *form = new formThird();
form->setWindowTitle("Nuevo Tercero");
addWorkWidget(form, form->windowTitle());
return form;
}
formBudget *MainWindow::createFormBudget()
{
auto *form = new formBudget();
form->setWindowTitle("Nuevo Presupusto");
addWorkWidget(form, form->windowTitle());
return form;
}
QAction* MainWindow::createAction(const QString& text, const QString& iconurl, const QString& objName)
{
QAction* act = new QAction(this);
act->setText(text);
act->setIcon(QIcon(iconurl));
if (objName == "")
act->setObjectName(text);
else
act->setObjectName(objName);
return act;
}
void MainWindow::tabCloseRequested(int index)
{
qDebug() << m_workspace->widget(index);
auto * form = static_cast<formBase*>(m_workspace->widget(index));
if (form->needsave())
{
QMessageBox msgBox;
msgBox.setText("Se necesita guardar el documento.");
msgBox.setInformativeText("Do you want to save your changes?");
msgBox.setIcon(QMessageBox::Warning);
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Save);
int ret = msgBox.exec();
if (ret == QMessageBox::Cancel)
return;
else if (ret == QMessageBox::Save)
form->save();
}
form->closeDocument();
m_workspace->removeTab(index);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
dApp->quit();
}
+106
View File
@@ -0,0 +1,106 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "ui_mainwindow.h"
#include <QMainWindow>
#include <QModelIndex>
#include "gui/SARibbon/src/SARibbonBar/SARibbonMainWindow.h"
class formProduct;
class formThird;
class formBudget;
class QTabWidget;
namespace Ui
{
class MainWindow;
}
//DWIDGET_USE_NAMESPACE
class MainWindow : public SARibbonMainWindow, private Ui::MainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
SARibbonBar* mRibbonBar { nullptr };
void setCompany(QString ID);
formProduct *createFormProduct();
formThird *createFormThird();
QDockWidget* createDockWidget(QString title, QString name, Qt::DockWidgetArea area);
QWidget* createWorkWidget( QString title, QString name );
void addWorkWidget(QWidget *tWidget, QString title);
private:
Ui::MainWindow *ui;
QTabWidget* m_workspace;
QAction *createAction(const QString &text, const QString &iconurl, const QString &objName="");
public slots:
formBudget* createFormBudget();
private slots:
void tabCloseRequested(int index);
protected:
void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H
Binary file not shown.
+74
View File
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>677</width>
<height>380</height>
</rect>
</property>
<property name="windowTitle">
<string>Editable Tree Model</string>
</property>
<property name="dockOptions">
<set>QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::AnimatedDocks|QMainWindow::ForceTabbedDocks</set>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="exitAction">
<property name="text">
<string>E&amp;xit</string>
</property>
<property name="shortcut">
<string>Ctrl+Q</string>
</property>
</action>
<action name="insertRowAction">
<property name="text">
<string>&amp;Insert Row</string>
</property>
<property name="shortcut">
<string>Ctrl+I, R</string>
</property>
</action>
<action name="removeRowAction">
<property name="text">
<string>&amp;Remove Row</string>
</property>
<property name="shortcut">
<string>Ctrl+R, R</string>
</property>
</action>
<action name="insertColumnAction">
<property name="text">
<string>Insert &amp;Column</string>
</property>
<property name="shortcut">
<string>Ctrl+I, C</string>
</property>
</action>
<action name="removeColumnAction">
<property name="text">
<string>R&amp;emove Column</string>
</property>
<property name="shortcut">
<string>Ctrl+R, C</string>
</property>
</action>
<action name="insertChildAction">
<property name="text">
<string>I&amp;nsert Child</string>
</property>
<property name="shortcut">
<string>Ctrl+N</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>
+43
View File
@@ -0,0 +1,43 @@
#include "qlistmodel.h"
#include <QIcon>
QListModel::QListModel(QObject *parent) :
QSqlQueryModel(parent)
{
}
QVariant QListModel::data(const QModelIndex &item, int role) const
{
if (!item.isValid())
return QVariant();
if(role == Qt::DecorationRole)
{
if(item.column() == 0)
{
if(item.data(13).toString() == "0") // Compuesto
{
return QIcon(":/resources/icons/box.svg");
}
else if(item.data(13).toString() == "1") // Materiales
{
return QIcon(":/resources/icons/blocks.svg");
}
else if(item.data(13).toString() == "2") // Mano de obra
{
return QIcon(":/resources/icons/helmet.svg");
}
else if(item.data(13).toString() == "3") // Maquinaria
{
return QIcon(":/resources/icons/gear.svg");
}
else if(item.data(13).toString() == "4") // Maquinaria
{
return QIcon(":/resources/icons/percentage.svg");
}
}
}
//return item.data(role);
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef QLISTMODEL_H
#define QLISTMODEL_H
#include <QSqlQueryModel>
class QListModel : public QSqlQueryModel
{
public:
QListModel(QObject *parent = Q_NULLPTR);
QVariant data(const QModelIndex &item, int role = Qt::DisplayRole) const override;
};
#endif // QLISTMODEL_H
+616
View File
@@ -0,0 +1,616 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
#include "treeitem.h"
#include "treemodel.h"
// Formatting helpers
namespace {
QString formatNumber(float value, int decimals = 2) {
static const QLocale locale("es_ES");
return locale.toString(value, 'f', decimals);
}
QString formatCurrency(float value) {
return formatNumber(value) + "";
}
QString formatPercentage(float value) {
return formatNumber(value) + " %";
}
}
//! [0]
TreeModel::TreeModel(const QStringList &headers, const QString &data, QObject *parent)
: QAbstractItemModel(parent)
{
QVector<QVariant> rootData;
foreach (QString header, headers)
rootData << header;
rootItem = new TreeItem(rootData);
//setupModelData(data.split(QString("\n")), rootItem);
// Insertar 20 filas vacias por defecto:
for (int i = 0; i < 20; i++)
{
rootItem->insertChildren(rootItem->childCount(), 1, rootItem->columnCount());
for (int column = 0; column < rootItem->columnCount(); ++column)
rootItem->child(rootItem->childCount() - 1)->setData(column, QVariant());
}
}
//! [0]
//! [1]
TreeModel::~TreeModel()
{
delete rootItem;
}
//! [1]
//! [2]
int TreeModel::columnCount(const QModelIndex & /* parent */) const
{
return rootItem->columnCount();
}
//! [2]
QVariant TreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
TreeItem *item = getItem(index);
const int col = index.column();
switch (role)
{
case Qt::DisplayRole:
return displayData(item, col);
case Qt::EditRole:
return editData(item, col);
case Qt::ForegroundRole:
return foregroundForItem(item, col);
case Qt::TextAlignmentRole:
return alignmentForColumn(col);
case Qt::FontRole:
/*
if(item->childCount() > 0)
{
QFont font = QFont("Helvetica", 9, QFont::Bold);
return QVariant::fromValue(font);
}
else
*/
return QVariant();
case Qt::BackgroundRole:
{
//if (item->childCount() > 0)
// return QVariant::fromValue(QColor(Qt::lightGray));
return QVariant();
}
case Qt::CheckStateRole:
/*
if (index.column() == 14)
return (QSqlQueryModel::data(index).toInt() != 0) ? Qt::Checked : Qt::Unchecked;
else*/
return QVariant();
case Qt::SizeHintRole:
{
int he = 24;
return QSize(80, he);
}
case Qt::DecorationRole:
return decorationForItem(item, col);
default:
break;
}
return item->data(role);
}
QVariant TreeModel::displayData(TreeItem *item, int column) const
{
const QString type = item->data(13).toString();
const QVariant rawData = item->data(column);
float value = rawData.isValid() ? rawData.toFloat() : 0.0f;
switch (column)
{
case 4:
case 5:
return formatNumber(value);
case 7:
case 8:
case 11:
case 12:
return formatCurrency(value);
case 9:
case 10:
return !type.isEmpty() ? formatPercentage(value) : rawData;
default:
return rawData;
}
}
QVariant TreeModel::editData(TreeItem *item, int column) const
{
return item->data(column);
}
QVariant TreeModel::foregroundForItem(TreeItem *item, int column) const
{
if (!item->parent() || !item->parent()->parent())
return (column == 1) ? QColor(Qt::darkBlue) : QVariant();
return (column == 1) ? QColor(Qt::blue) : QColor(Qt::gray);
}
QVariant TreeModel::alignmentForColumn(int column) const
{
switch (column) {
case 4:
case 5:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
return int(Qt::AlignRight | Qt::AlignTop);
default:
return int(Qt::AlignLeft | Qt::AlignTop);
}
}
QVariant TreeModel::decorationForItem(TreeItem *item, int column) const
{
/*
0 Sin clasificar
1 Mano de obra
2 Maquinaria
3 Materiales
4 Componentes adicionales de residuo
5 Clasificación de residuo
....
*/
if (column != 0)
return QVariant();
static const QMap<QString, QString> iconMap = {
{"CO", ":/resources/icons/box.svg"},
{"MO", ":/resources/icons/helmet.svg"},
{"MQ", ":/resources/icons/gear.svg"},
{"MT", ":/resources/icons/blocks.svg"},
{"%", ":/resources/icons/percentage.svg"}
};
const QString type = item->data(13).toString();
return iconMap.contains(type) ? QIcon(iconMap[type]) : QVariant();
}
//! [3]
Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
TreeItem *item = getItem(index);
const int col = index.column();
const bool isLeaf = (item->childCount() == 0);
// Editable columns
static const QVector<int> leafEditable = {0, 1, 2, 3, 4, 6, 7, 9, 10};
static const QVector<int> branchEditable = {0, 1, 2, 3, 4, 6, 9, 10};
if ((isLeaf && leafEditable.contains(col)) ||
(!isLeaf && branchEditable.contains(col))) {
flags |= Qt::ItemIsEditable;
}
return flags;
/*
if (!index.isValid())
return Qt::NoItemFlags;
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
TreeItem *item = getItem(index);
if(item->childCount() == 0)
{
switch (index.column())
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
case 7:
case 9:
case 10:
{
flags |= Qt::ItemIsEditable;
}
}
}
else
{
switch (index.column())
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
case 9:
case 10:
{
flags |= Qt::ItemIsEditable;
}
}
}
return flags;*/
}
//! [3]
//! [4]
TreeItem *TreeModel::getItem(const QModelIndex &index) const
{
if (index.isValid())
{
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
if (item)
return item;
}
return rootItem;
}
//! [4]
QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return rootItem->data(section);
return QVariant();
}
//! [5]
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid() && parent.column() != 0)
return QModelIndex();
//! [5]
//! [6]
TreeItem *parentItem = getItem(parent);
TreeItem *childItem = parentItem->child(row);
return childItem ? createIndex(row, column, childItem) : QModelIndex();
}
//! [6]
bool TreeModel::insertColumns(int position, int columns, const QModelIndex &parent)
{
beginInsertColumns(parent, position, position + columns - 1);
const bool success = rootItem->insertColumns(position, columns);
endInsertColumns();
return success;
}
bool TreeModel::insertRows(int position, int rows, const QModelIndex &parent)
{
TreeItem *parentItem = getItem(parent);
beginInsertRows(parent, position, position + rows - 1);
const bool success = parentItem->insertChildren(position, rows, rootItem->columnCount());
endInsertRows();
return success;
}
//! [7]
QModelIndex TreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
TreeItem *childItem = getItem(index);
TreeItem *parentItem = childItem->parent();
return (parentItem == rootItem) ? QModelIndex() :
createIndex(parentItem->childNumber(), 0, parentItem);
}
//! [7]
bool TreeModel::removeColumns(int position, int columns, const QModelIndex &parent)
{
beginRemoveColumns(parent, position, position + columns - 1);
const bool success = rootItem->removeColumns(position, columns);
endRemoveColumns();
if (rootItem->columnCount() == 0)
removeRows(0, rowCount());
return success;
}
bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent)
{
TreeItem *parentItem = getItem(parent);
beginRemoveRows(parent, position, position + rows - 1);
const bool success = parentItem->removeChildren(position, rows);
endRemoveRows();
return success;
}
//! [8]
int TreeModel::rowCount(const QModelIndex &parent) const
{
return getItem(parent)->childCount();
}
//! [8]
bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() || role != Qt::EditRole)
return false;
TreeItem *item = getItem(index);
const int col = index.column();
if (!item->setData(col, value))
return false;
emit dataChanged(index, index, {role});
switch (col) {
case 0:
if (item->childCount() > 0)
codify(item);
break;
case 4:
updateQuantities(item, index.parent());
break;
case 7:
case 9:
case 10:
updateCalculations(item, col);
break;
}
return true;
}
void TreeModel::codify(TreeItem *item)
{
for (int i = 0; i < item->childCount(); ++i) {
TreeItem *child = item->child(i);
child->setData(0, QString("%1.%2").arg(item->data(0).toString()).arg(i + 1));
if (child->childCount() > 0)
codify(child);
}
}
void TreeModel::updateQuantities(TreeItem *item, const QModelIndex &parent)
{
if (parent.isValid()) {
TreeItem *parentItem = getItem(parent);
item->setData(5, item->data(4).toFloat() * parentItem->data(5).toFloat());
} else {
item->setData(5, item->data(4));
}
calculateRow(item);
}
void TreeModel::updateCalculations(TreeItem *item, int column)
{
if (item->childCount() > 0)
setTreeValues(item, column);
calculateRow(item);
}
void TreeModel::setTreeValues(TreeItem *item, int column)
{
for(int i = 0; i < item->childCount(); ++i)
{
TreeItem * chil = item->child(i);
chil->setData(column, item->data(column));
if(chil->childCount() > 0)
setTreeValues(chil, column);
}
}
void TreeModel::calculateParent(TreeItem *item)
{
if (!item || !item->parent()) return;
float pcu = 0, pct = 0, pvt = 0;
for(int i = 0; i<item->childCount(); ++i)
{
TreeItem * child = item->child(i);
pcu += child->data(4).toFloat() * child->data(7).toFloat();
pct += child->data(8).toFloat();
pvt += child->data(11).toFloat();
}
item->setData(7, pcu);
item->setData(8, pct);
item->setData(11, pvt);
item->setData(12, pvt - pct);
if(item->parent() && item->parent()->parent())
calculateParent(item->parent());
}
void TreeModel::calculateRow(TreeItem *item)
{
if(item->childCount() > 0)
{
for(int i = 0; i<item->childCount(); ++i)
{
TreeItem * child = item->child(i);
child->setData(5, child->data(4).toFloat() * item->data(5).toFloat());
calculateRow(child);
}
}
else
{
float cu = item->data(4).toFloat();
float ct = item->data(5).toFloat();
float pcu = item->data(7).toFloat();
float pct = ct * pcu;
float pro = item->data(9).toFloat();
float dis = item->data(10).toFloat();
float pvt = pct * (1 + pro / 100) * (1 - dis / 100);
item->setData(8, pct);
item->setData(11, pvt);
item->setData(12, pvt - pct);
}
if(item->parent() && item->parent()->parent())
calculateParent(item->parent());
}
bool TreeModel::setHeaderData(int section, Qt::Orientation orientation,
const QVariant &value, int role)
{
if (role != Qt::EditRole || orientation != Qt::Horizontal)
return false;
bool result = rootItem->setData(section, value);
if (result)
emit headerDataChanged(orientation, section, section);
return result;
}
void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent)
{
QList<TreeItem*> parents;
QList<int> indentations;
parents << parent;
indentations << 0;
int number = 0;
while (number < lines.count())
{
int position = 0;
while (position < lines[number].length())
{
if (lines[number].at(position) != ' ')
break;
++position;
}
QString lineData = lines[number].mid(position).trimmed();
if (!lineData.isEmpty())
{
// Read the column data from the rest of the line.
QStringList columnStrings = lineData.split("\t", Qt::SkipEmptyParts);
QVector<QVariant> columnData;
for (int column = 0; column < columnStrings.count(); ++column)
columnData << columnStrings[column];
if (position > indentations.last())
{
// The last child of the current parent is now the new parent
// unless the current parent has no children.
if (parents.last()->childCount() > 0)
{
parents << parents.last()->child(parents.last()->childCount()-1);
indentations << position;
}
}
else
{
while (position < indentations.last() && parents.count() > 0)
{
parents.pop_back();
indentations.pop_back();
}
}
// Append a new item to the current parent's list of children.
TreeItem *parent = parents.last();
parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
for (int column = 0; column < columnData.size(); ++column)
parent->child(parent->childCount() - 1)->setData(column, columnData[column]);
}
++number;
}
}
+117
View File
@@ -0,0 +1,117 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef TREEMODEL_H
#define TREEMODEL_H
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
class TreeItem;
//! [0]
class TreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
TreeModel(const QStringList &headers, const QString &data, QObject *parent = nullptr);
~TreeModel() override;
//! [0]
//! [1]
QVariant data(const QModelIndex &index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
//! [1]
//! [2]
Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole) override;
bool insertColumns(int position, int columns, const QModelIndex &parent = QModelIndex()) override;
bool removeColumns(int position, int columns, const QModelIndex &parent = QModelIndex()) override;
bool insertRows(int position, int rows, const QModelIndex &parent = QModelIndex()) override;
bool removeRows(int position, int rows, const QModelIndex &parent = QModelIndex()) override;
signals:
void DataChanged(TreeItem &item, const QModelIndex &index, const int role);
void onGetDataEdit(const QModelIndex &index, QVariant &value) const;
void onGetDataTextColor(const QModelIndex &index, QVariant &value) const;
private:
void setupModelData(const QStringList &lines, TreeItem *parent);
TreeItem *getItem(const QModelIndex &index) const;
TreeItem *rootItem;
void updateQuantities(TreeItem *item, const QModelIndex &parent);
void updateCalculations(TreeItem *item, int column);
void calculateRow(TreeItem *item);
void calculateParent(TreeItem *item);
void setTreeValues(TreeItem *item, int column);
void codify(TreeItem *item);
QVariant displayData(TreeItem *item, int column) const;
QVariant editData(TreeItem *item, int column) const;
QVariant alignmentForColumn(int column) const;
QVariant decorationForItem(TreeItem *item, int column) const;
QVariant foregroundForItem(TreeItem *item, int column) const;
};
//! [2]
#endif // TREEMODEL_H
Binary file not shown.