code format

This commit is contained in:
2022-12-14 14:14:33 +03:00
parent 09e5342956
commit cdb02fc9be
278 changed files with 15371 additions and 12176 deletions

View File

@@ -1,6 +1,7 @@
#include "qad_sql_table.h"
#include "sql_table_plugin.h"
#include "sql_record_plugin.h"
#include "sql_table_plugin.h"
QADSQLTable::QADSQLTable(QObject * parent): QObject(parent) {
@@ -9,7 +10,7 @@ QADSQLTable::QADSQLTable(QObject * parent): QObject(parent) {
}
QList<QDesignerCustomWidgetInterface * > QADSQLTable::customWidgets() const {
QList<QDesignerCustomWidgetInterface *> QADSQLTable::customWidgets() const {
return m_widgets;
}

View File

@@ -1,23 +1,24 @@
#ifndef QAD_SQL_TABLE_H
#define QAD_SQL_TABLE_H
#include <QtDesigner/QtDesigner>
#include <QtCore/qplugin.h>
#include <QtDesigner/QtDesigner>
class QADSQLTable: public QObject, public QDesignerCustomWidgetCollectionInterface
{
class QADSQLTable
: public QObject
, public QDesignerCustomWidgetCollectionInterface {
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetCollectionInterface)
#if QT_VERSION >= 0x050000
Q_PLUGIN_METADATA(IID "qad.sql_table")
#endif
public:
explicit QADSQLTable(QObject * parent = 0);
virtual QList<QDesignerCustomWidgetInterface * > customWidgets() const;
virtual QList<QDesignerCustomWidgetInterface *> customWidgets() const;
private:
QList<QDesignerCustomWidgetInterface * > m_widgets;
QList<QDesignerCustomWidgetInterface *> m_widgets;
};
#endif // QAD_SQL_TABLE_H

View File

@@ -1,5 +1,7 @@
#include "sql_record_widget.h"
#include "sql_record_plugin.h"
#include "sql_record_widget.h"
#include <QtCore/QtPlugin>
@@ -9,8 +11,7 @@ SQLRecordPlugin::SQLRecordPlugin(QObject * parent): QObject(parent) {
void SQLRecordPlugin::initialize(QDesignerFormEditorInterface * /* core */) {
if (m_initialized)
return;
if (m_initialized) return;
// Add extension registrations, etc. here
@@ -66,4 +67,3 @@ QString SQLRecordPlugin::domXml() const {
QString SQLRecordPlugin::includeFile() const {
return QLatin1String("sql_record_widget.h");
}

View File

@@ -8,8 +8,9 @@
# include <QDesignerCustomWidgetInterface>
#endif
class SQLRecordPlugin: public QObject, public QDesignerCustomWidgetInterface
{
class SQLRecordPlugin
: public QObject
, public QDesignerCustomWidgetInterface {
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetInterface)
@@ -30,7 +31,6 @@ public:
private:
bool m_initialized;
};
#endif // SQLRECORDPLUGIN_H

View File

@@ -1,5 +1,7 @@
#include "sql_table_widget.h"
#include "sql_table_plugin.h"
#include "sql_table_widget.h"
#include <QtCore/QtPlugin>
@@ -9,8 +11,7 @@ SQLTablePlugin::SQLTablePlugin(QObject * parent): QObject(parent) {
void SQLTablePlugin::initialize(QDesignerFormEditorInterface * /* core */) {
if (m_initialized)
return;
if (m_initialized) return;
// Add extension registrations, etc. here
@@ -66,4 +67,3 @@ QString SQLTablePlugin::domXml() const {
QString SQLTablePlugin::includeFile() const {
return QLatin1String("sql_table_widget.h");
}

View File

@@ -8,8 +8,9 @@
# include <QDesignerCustomWidgetInterface>
#endif
class SQLTablePlugin: public QObject, public QDesignerCustomWidgetInterface
{
class SQLTablePlugin
: public QObject
, public QDesignerCustomWidgetInterface {
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetInterface)
@@ -30,7 +31,6 @@ public:
private:
bool m_initialized;
};
#endif // SQLTABLEPLUGIN_H

View File

@@ -1,15 +1,16 @@
#include "sql_record_widget.h"
#include <qpiconfig.h>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlError>
#include <QCheckBox>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QLabel>
#include <QDoubleSpinBox>
#include <QCheckBox>
#include <QLineEdit>
#include <QComboBox>
#include <QSqlError>
#include <QSqlField>
#include <QSqlRecord>
#include <colorbutton.h>
#include <qpiconfig.h>
#include <qpiconfigvaluewidget.h>
@@ -20,15 +21,14 @@ SQLRecordWidget::SQLRecordWidget(QWidget * parent): QWidget(parent) {
}
SQLRecordWidget::~SQLRecordWidget() {
}
SQLRecordWidget::~SQLRecordWidget() {}
void SQLRecordWidget::setRecord(const QSqlRecord & q, bool full_update) {
//qDebug() << (q.count() - hidden.size()) << (layout()->count() / 2);
// qDebug() << (q.count() - hidden.size()) << (layout()->count() / 2);
if (full_update || (q.count() - hidden.size()) != (layout()->count() / 2)) createWidgets(q);
for (int i = 0; i < q.count(); ++i) {
QSqlField f = q.field(i);
QSqlField f = q.field(i);
QWidget * val = 0;
for (int w = 0; w < cws.size(); ++w)
if (cws[w]->objectName() == f.name()) {
@@ -36,41 +36,41 @@ void SQLRecordWidget::setRecord(const QSqlRecord & q, bool full_update) {
break;
}
if (val == 0) continue;
if (qobject_cast<QLineEdit * >(val)) {
if (qobject_cast<QLineEdit *>(val)) {
if (relations.contains(f.name())) {
bool ok = false;
int sv(f.value().toInt(&ok));
if (!ok)
qobject_cast<QLineEdit * >(val)->setText("");
qobject_cast<QLineEdit *>(val)->setText("");
else {
QList<QPair<int, QString> > & rv(relations[f.name()]);
QList<QPair<int, QString>> & rv(relations[f.name()]);
for (int j = 0; j < rv.size(); ++j) {
if (sv == rv[j].first) {
qobject_cast<QLineEdit * >(val)->setText(rv[j].second);
qobject_cast<QLineEdit *>(val)->setText(rv[j].second);
break;
}
}
}
} else
qobject_cast<QLineEdit * >(val)->setText(f.value().toString());
qobject_cast<QLineEdit *>(val)->setText(f.value().toString());
}
if (qobject_cast<QCheckBox * >(val)) qobject_cast<QCheckBox * >(val)->setChecked(f.value().toBool());
if (qobject_cast<QDoubleSpinBox * >(val)) qobject_cast<QDoubleSpinBox * >(val)->setValue(f.value().toDouble());
if (qobject_cast<ColorButton * >(val)) qobject_cast<ColorButton * >(val)->setColor(QColor::fromRgba(f.value().toUInt()));
if (qobject_cast<StringListEdit * >(val)) {
if (qobject_cast<QCheckBox *>(val)) qobject_cast<QCheckBox *>(val)->setChecked(f.value().toBool());
if (qobject_cast<QDoubleSpinBox *>(val)) qobject_cast<QDoubleSpinBox *>(val)->setValue(f.value().toDouble());
if (qobject_cast<ColorButton *>(val)) qobject_cast<ColorButton *>(val)->setColor(QColor::fromRgba(f.value().toUInt()));
if (qobject_cast<StringListEdit *>(val)) {
QString s = f.value().toString();
qobject_cast<StringListEdit * >(val)->setValue(s.isEmpty() ? QStringList() : s.split(";"));
qobject_cast<StringListEdit *>(val)->setValue(s.isEmpty() ? QStringList() : s.split(";"));
}
if (qobject_cast<QComboBox * >(val)) {
if (qobject_cast<QComboBox *>(val)) {
bool ok = false;
int sv(f.value().toInt(&ok));
if (!ok)
((QComboBox*)val)->setCurrentIndex(-1);
((QComboBox *)val)->setCurrentIndex(-1);
else {
QList<QPair<int, QString> > & rv(relations[f.name()]);
QList<QPair<int, QString>> & rv(relations[f.name()]);
for (int j = 0; j < rv.size(); ++j) {
if (sv == rv[j].first) {
((QComboBox*)val)->setCurrentIndex(j);
((QComboBox *)val)->setCurrentIndex(j);
break;
}
}
@@ -81,25 +81,39 @@ void SQLRecordWidget::setRecord(const QSqlRecord & q, bool full_update) {
void SQLRecordWidget::setFixedValue(const QString & name, const QVariant & value) {
foreach (QWidget * w, cws) {
foreach(QWidget * w, cws) {
if (w->objectName() != name) continue;
if (qobject_cast<QLineEdit * >(w)) {qobject_cast<QLineEdit * >(w)->setText(value.toString()); qobject_cast<QLineEdit * >(w)->setReadOnly(true);}
if (qobject_cast<QCheckBox * >(w)) {qobject_cast<QCheckBox * >(w)->setChecked(value.toBool()); w->setEnabled(false);}
if (qobject_cast<QDoubleSpinBox * >(w)) {qobject_cast<QDoubleSpinBox * >(w)->setValue(value.toDouble()); qobject_cast<QDoubleSpinBox * >(w)->setReadOnly(true);}
if (qobject_cast<ColorButton * >(w)) {qobject_cast<ColorButton * >(w)->setColor(QColor::fromRgba(value.toUInt())); qobject_cast<ColorButton * >(w)->setEnabled(false);}
if (qobject_cast<StringListEdit * >(w)) {qobject_cast<StringListEdit * >(w)->setValue(QStringList()); qobject_cast<StringListEdit * >(w)->setEnabled(false);}
if (qobject_cast<QLineEdit *>(w)) {
qobject_cast<QLineEdit *>(w)->setText(value.toString());
qobject_cast<QLineEdit *>(w)->setReadOnly(true);
}
if (qobject_cast<QCheckBox *>(w)) {
qobject_cast<QCheckBox *>(w)->setChecked(value.toBool());
w->setEnabled(false);
}
if (qobject_cast<QDoubleSpinBox *>(w)) {
qobject_cast<QDoubleSpinBox *>(w)->setValue(value.toDouble());
qobject_cast<QDoubleSpinBox *>(w)->setReadOnly(true);
}
if (qobject_cast<ColorButton *>(w)) {
qobject_cast<ColorButton *>(w)->setColor(QColor::fromRgba(value.toUInt()));
qobject_cast<ColorButton *>(w)->setEnabled(false);
}
if (qobject_cast<StringListEdit *>(w)) {
qobject_cast<StringListEdit *>(w)->setValue(QStringList());
qobject_cast<StringListEdit *>(w)->setEnabled(false);
}
}
}
void SQLRecordWidget::clearValues() {
foreach (QWidget * w, cws) {
if (qobject_cast<QLineEdit * >(w)) qobject_cast<QLineEdit * >(w)->setText(QString());
if (qobject_cast<QCheckBox * >(w)) qobject_cast<QCheckBox * >(w)->setChecked(false);
if (qobject_cast<QDoubleSpinBox * >(w)) qobject_cast<QDoubleSpinBox * >(w)->setValue(0.);
if (qobject_cast<ColorButton * >(w)) qobject_cast<ColorButton * >(w)->setColor(Qt::black);
if (qobject_cast<StringListEdit * >(w)) qobject_cast<StringListEdit * >(w)->setValue(QStringList());
foreach(QWidget * w, cws) {
if (qobject_cast<QLineEdit *>(w)) qobject_cast<QLineEdit *>(w)->setText(QString());
if (qobject_cast<QCheckBox *>(w)) qobject_cast<QCheckBox *>(w)->setChecked(false);
if (qobject_cast<QDoubleSpinBox *>(w)) qobject_cast<QDoubleSpinBox *>(w)->setValue(0.);
if (qobject_cast<ColorButton *>(w)) qobject_cast<ColorButton *>(w)->setColor(Qt::black);
if (qobject_cast<StringListEdit *>(w)) qobject_cast<StringListEdit *>(w)->setValue(QStringList());
}
}
@@ -113,28 +127,26 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) {
lay->setLabelAlignment(Qt::AlignRight);
lay->setContentsMargins(0, 0, 0, 0);
setLayout(lay);
//qDebug() << "createWidgets" << q.count();
// qDebug() << "createWidgets" << q.count();
for (int i = 0; i < q.count(); ++i) {
QSqlField f = q.field(i);
if (hidden.contains(f.name())) continue;
QPair<QString, QString> ctr = trColumn(f.name());
QWidget * val = 0;
QWidget * val = 0;
if (relations.contains(f.name())) {
if (ro) {
val = new QLineEdit();
} else {
val = new QComboBox();
QList<QPair<int, QString> > & rv(relations[f.name()]);
QList<QPair<int, QString>> & rv(relations[f.name()]);
bool ok = false;
int sv(f.value().toInt(&ok));
for (int j = 0; j < rv.size(); ++j) {
((QComboBox*)val)->addItem(rv[j].second, rv[j].first);
((QComboBox *)val)->addItem(rv[j].second, rv[j].first);
if (ok)
if (sv == rv[j].first)
((QComboBox*)val)->setCurrentIndex(j);
if (sv == rv[j].first) ((QComboBox *)val)->setCurrentIndex(j);
}
if (!ok)
((QComboBox*)val)->setCurrentIndex(-1);
if (!ok) ((QComboBox *)val)->setCurrentIndex(-1);
}
} else {
switch (fieldType(f)) {
@@ -144,27 +156,25 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) {
case QVariant::ULongLong:
case QVariant::Double:
val = new QDoubleSpinBox();
((QDoubleSpinBox*)val)->setRange(-1E+99, 1E+99);
((QDoubleSpinBox*)val)->setDecimals(3); break;
case QVariant::String:
val = new QLineEdit(); break;
case QVariant::Bool:
val = new QCheckBox(); break;
((QDoubleSpinBox *)val)->setRange(-1E+99, 1E+99);
((QDoubleSpinBox *)val)->setDecimals(3);
break;
case QVariant::String: val = new QLineEdit(); break;
case QVariant::Bool: val = new QCheckBox(); break;
case QVariant::Color:
val = new ColorButton();
((ColorButton*)val)->setUseAlphaChannel(true);
((ColorButton*)val)->setUseNativeDialog(true);
break;
case QVariant::StringList:
val = new StringListEdit();
((ColorButton *)val)->setUseAlphaChannel(true);
((ColorButton *)val)->setUseNativeDialog(true);
break;
case QVariant::StringList: val = new StringListEdit(); break;
default: break;
}
if (f.type() == QVariant::String || f.type() == QVariant::StringList) val->setProperty("_string", true);
}
if (val != 0) {
QString lt = ctr.first.left(1).toUpper() + ctr.first.right(ctr.first.length() - 1);
while (lt.endsWith("_")) lt.chop(1);
while (lt.endsWith("_"))
lt.chop(1);
QLabel * lbl = new QLabel(lt + ":");
lbl->setToolTip(ctr.second);
cws << lbl;
@@ -172,8 +182,7 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) {
cws << val;
lay->addRow(lbl, val);
} else {
if (!hidden.contains(ctr.first))
hidden << ctr.first;
if (!hidden.contains(ctr.first)) hidden << ctr.first;
}
}
updateWidgets();
@@ -182,13 +191,13 @@ void SQLRecordWidget::createWidgets(const QSqlRecord & q) {
void SQLRecordWidget::updateWidgets() {
foreach (QWidget * w, cws) {
if (qobject_cast<QLineEdit * >(w)) qobject_cast<QLineEdit * >(w)->setReadOnly(ro);
if (qobject_cast<QCheckBox * >(w)) qobject_cast<QCheckBox * >(w)->setEnabled(!ro);
if (qobject_cast<QDoubleSpinBox * >(w)) qobject_cast<QDoubleSpinBox * >(w)->setReadOnly(ro);
if (qobject_cast<ColorButton * >(w)) qobject_cast<ColorButton * >(w)->setEnabled(!ro);
if (qobject_cast<StringListEdit * >(w)) qobject_cast<StringListEdit * >(w)->setEnabled(!ro);
if (qobject_cast<QComboBox * >(w)) qobject_cast<QComboBox * >(w)->setEnabled(!ro);
foreach(QWidget * w, cws) {
if (qobject_cast<QLineEdit *>(w)) qobject_cast<QLineEdit *>(w)->setReadOnly(ro);
if (qobject_cast<QCheckBox *>(w)) qobject_cast<QCheckBox *>(w)->setEnabled(!ro);
if (qobject_cast<QDoubleSpinBox *>(w)) qobject_cast<QDoubleSpinBox *>(w)->setReadOnly(ro);
if (qobject_cast<ColorButton *>(w)) qobject_cast<ColorButton *>(w)->setEnabled(!ro);
if (qobject_cast<StringListEdit *>(w)) qobject_cast<StringListEdit *>(w)->setEnabled(!ro);
if (qobject_cast<QComboBox *>(w)) qobject_cast<QComboBox *>(w)->setEnabled(!ro);
}
}
@@ -212,7 +221,7 @@ QVariant::Type SQLRecordWidget::fieldType(const QSqlField & f) {
void SQLRecordWidget::addTranslation(const QString & file) {
QPIConfig conf(file, QIODevice::ReadOnly, QPIConfig::Config);
QPIConfig::Branch ae = conf.allLeaves();
foreach (QPIConfig::Entry * e, ae)
foreach(QPIConfig::Entry * e, ae)
translates[e->name()] = QPair<QString, QString>(e->value(), e->comment());
}
@@ -220,50 +229,52 @@ void SQLRecordWidget::addTranslation(const QString & file) {
QString SQLRecordWidget::getValuesQuery() const {
QString ret("(");
bool first = true;
foreach (QWidget * w, cws) {
foreach(QWidget * w, cws) {
QWidget * vw(0);
if (qobject_cast<QLineEdit * >(w)) {if (!qobject_cast<QLineEdit * >(w)->text().isEmpty()) vw = w;}
if (qobject_cast<QCheckBox * >(w)) vw = w;
if (qobject_cast<QDoubleSpinBox * >(w)) vw = w;
if (qobject_cast<ColorButton * >(w)) vw = w;
if (qobject_cast<StringListEdit * >(w)) vw = w;
if (qobject_cast<QComboBox * >(w)) vw = w;
if (qobject_cast<QLineEdit *>(w)) {
if (!qobject_cast<QLineEdit *>(w)->text().isEmpty()) vw = w;
}
if (qobject_cast<QCheckBox *>(w)) vw = w;
if (qobject_cast<QDoubleSpinBox *>(w)) vw = w;
if (qobject_cast<ColorButton *>(w)) vw = w;
if (qobject_cast<StringListEdit *>(w)) vw = w;
if (qobject_cast<QComboBox *>(w)) vw = w;
if (vw == 0) continue;
if (!first) ret += ",";
first = false;
ret += vw->objectName();
}
ret += ") VALUES (";
foreach (QWidget * w, cws) {
foreach(QWidget * w, cws) {
QWidget * vw(0);
if (qobject_cast<QLineEdit * >(w)) {
if (!qobject_cast<QLineEdit * >(w)->text().isEmpty()) {
vw = w;
if (qobject_cast<QLineEdit *>(w)) {
if (!qobject_cast<QLineEdit *>(w)->text().isEmpty()) {
vw = w;
bool q = w->property("_string").toBool();
if (q) ret += "'";
ret += qobject_cast<QLineEdit * >(w)->text();
ret += qobject_cast<QLineEdit *>(w)->text();
if (q) ret += "'";
}
}
if (qobject_cast<QCheckBox * >(w)) {
if (qobject_cast<QCheckBox *>(w)) {
vw = w;
ret += qobject_cast<QCheckBox * >(w)->isChecked() ? "1" : "0";
ret += qobject_cast<QCheckBox *>(w)->isChecked() ? "1" : "0";
}
if (qobject_cast<QDoubleSpinBox * >(w)) {
if (qobject_cast<QDoubleSpinBox *>(w)) {
vw = w;
ret += QString::number(qobject_cast<QDoubleSpinBox * >(w)->value());
ret += QString::number(qobject_cast<QDoubleSpinBox *>(w)->value());
}
if (qobject_cast<ColorButton * >(w)) {
if (qobject_cast<ColorButton *>(w)) {
vw = w;
ret += QString::number(qobject_cast<ColorButton * >(w)->color().rgba());
ret += QString::number(qobject_cast<ColorButton *>(w)->color().rgba());
}
if (qobject_cast<StringListEdit * >(w)) {
if (qobject_cast<StringListEdit *>(w)) {
vw = w;
ret += "'" + qobject_cast<StringListEdit * >(w)->value().join(";") + "'";
ret += "'" + qobject_cast<StringListEdit *>(w)->value().join(";") + "'";
}
if (qobject_cast<QComboBox * >(w)) {
if (qobject_cast<QComboBox *>(w)) {
vw = w;
ret += ((QComboBox*)w)->itemData(((QComboBox*)w)->currentIndex(), Qt::UserRole).toString();
ret += ((QComboBox *)w)->itemData(((QComboBox *)w)->currentIndex(), Qt::UserRole).toString();
}
if (vw == 0) continue;
ret += ",";
@@ -277,38 +288,34 @@ QString SQLRecordWidget::getValuesQuery() const {
QString SQLRecordWidget::getUpdateQuery() const {
QString ret;
bool first = true;
foreach (QWidget * w, cws) {
foreach(QWidget * w, cws) {
QWidget * vw(0);
if (qobject_cast<QLineEdit * >(w)) vw = w;
if (qobject_cast<QCheckBox * >(w)) vw = w;
if (qobject_cast<QDoubleSpinBox * >(w)) vw = w;
if (qobject_cast<ColorButton * >(w)) vw = w;
if (qobject_cast<StringListEdit * >(w)) vw = w;
if (qobject_cast<QComboBox * >(w)) vw = w;
if (qobject_cast<QLineEdit *>(w)) vw = w;
if (qobject_cast<QCheckBox *>(w)) vw = w;
if (qobject_cast<QDoubleSpinBox *>(w)) vw = w;
if (qobject_cast<ColorButton *>(w)) vw = w;
if (qobject_cast<StringListEdit *>(w)) vw = w;
if (qobject_cast<QComboBox *>(w)) vw = w;
if (vw == 0) continue;
if (!first) ret += ",";
first = false;
ret += vw->objectName() + "=";
if (qobject_cast<QLineEdit * >(w)) {
if (qobject_cast<QLineEdit * >(w)->text().isEmpty())
if (qobject_cast<QLineEdit *>(w)) {
if (qobject_cast<QLineEdit *>(w)->text().isEmpty())
ret += "null";
else {
bool q = w->property("_string").toBool();
if (q) ret += "'";
ret += qobject_cast<QLineEdit * >(w)->text();
ret += qobject_cast<QLineEdit *>(w)->text();
if (q) ret += "'";
}
}
if (qobject_cast<QCheckBox * >(w))
ret += qobject_cast<QCheckBox * >(w)->isChecked() ? "1" : "0";
if (qobject_cast<QDoubleSpinBox * >(w))
ret += QString::number(qobject_cast<QDoubleSpinBox * >(w)->value());
if (qobject_cast<ColorButton * >(w))
ret += QString::number(qobject_cast<ColorButton * >(w)->color().rgba());
if (qobject_cast<StringListEdit * >(w))
ret += "'" + qobject_cast<StringListEdit * >(w)->value().join(";") + "'";
if (qobject_cast<QComboBox * >(w)) {
QString cd = ((QComboBox*)w)->itemData(((QComboBox*)w)->currentIndex(), Qt::UserRole).toString();
if (qobject_cast<QCheckBox *>(w)) ret += qobject_cast<QCheckBox *>(w)->isChecked() ? "1" : "0";
if (qobject_cast<QDoubleSpinBox *>(w)) ret += QString::number(qobject_cast<QDoubleSpinBox *>(w)->value());
if (qobject_cast<ColorButton *>(w)) ret += QString::number(qobject_cast<ColorButton *>(w)->color().rgba());
if (qobject_cast<StringListEdit *>(w)) ret += "'" + qobject_cast<StringListEdit *>(w)->value().join(";") + "'";
if (qobject_cast<QComboBox *>(w)) {
QString cd = ((QComboBox *)w)->itemData(((QComboBox *)w)->currentIndex(), Qt::UserRole).toString();
ret += cd.isEmpty() ? "null" : cd;
}
}
@@ -327,29 +334,27 @@ void SQLRecordWidget::updateRelations() {
if (!db.isOpen()) return;
for (int i = 0; i < relations_src.size(); ++i) {
QSqlQuery q(QString("SELECT %1,%2 FROM %3").arg(relations_src[i].key, relations_src[i].ocol, relations_src[i].table), db);
QList<QPair<int, QString> > cr;
QList<QPair<int, QString>> cr;
while (q.next())
cr << QPair<int, QString>(q.value(0).toInt(), q.value(1).toString());
relations[relations_src[i].tcol] = cr;
}
QFormLayout * lay = (QFormLayout*)layout();
QFormLayout * lay = (QFormLayout *)layout();
if (!lay) return;
for (int i = 0; i < lay->rowCount(); ++i) {
QString name = lay->itemAt(i, QFormLayout::FieldRole)->widget()->objectName();
if (hidden.contains(name)) continue;
QComboBox * val = qobject_cast<QComboBox*>(lay->itemAt(i, QFormLayout::FieldRole)->widget());
QComboBox * val = qobject_cast<QComboBox *>(lay->itemAt(i, QFormLayout::FieldRole)->widget());
if (!val) continue;
if (!relations.contains(name)) continue;
QList<QPair<int, QString> > & rv(relations[name]);
QList<QPair<int, QString>> & rv(relations[name]);
bool ok = false;
int sv(val->itemData(val->currentIndex()).toInt());
val->clear();
for (int j = 0; j < rv.size(); ++j) {
val->addItem(rv[j].second, rv[j].first);
if (sv == rv[j].first)
val->setCurrentIndex(j);
if (sv == rv[j].first) val->setCurrentIndex(j);
}
if (!ok)
val->setCurrentIndex(-1);
if (!ok) val->setCurrentIndex(-1);
}
}

View File

@@ -1,85 +1,109 @@
/*
QAD - Qt ADvanced
QAD - Qt ADvanced
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SQL_RECORD_WIDGET_H
#define SQL_RECORD_WIDGET_H
#include <QWidget>
#include <QSqlQuery>
#include <QSqlField>
#include <QVariant>
#include "qad_sql_table_export.h"
#include <QMap>
#include <QSet>
#include "qad_sql_table_export.h"
#include <QSqlField>
#include <QSqlQuery>
#include <QVariant>
#include <QWidget>
class QAD_SQL_TABLE_EXPORT SQLRecordWidget: public QWidget {
Q_OBJECT
public:
SQLRecordWidget(QWidget * parent = 0);
~SQLRecordWidget();
void setRecord(const QSqlRecord & q, bool full_update = false);
void setReadOnly(bool yes) {ro = yes; updateWidgets();}
void setReadOnly(bool yes) {
ro = yes;
updateWidgets();
}
void setFixedValue(const QString & name, const QVariant & value);
void setTypeForName(const QString & name, const QString & type) {ftypes[name] = type;}
void setTypeForName(const QString & name, const QString & type) { ftypes[name] = type; }
void clearValues();
void removeWidgets() {qDeleteAll(cws); cws.clear();}
void hideColumn(const QString & col) {hidden << col;}
void showColumn(const QString & col) {hidden.remove(col);}
void showColumns() {hidden.clear();}
void addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column) {relations_src << RelationSrc(this_column, other_table, other_key, other_column); updateRelations();}
void removeRelations() {relations_src.clear(); updateRelations();}
void removeWidgets() {
qDeleteAll(cws);
cws.clear();
}
void hideColumn(const QString & col) { hidden << col; }
void showColumn(const QString & col) { hidden.remove(col); }
void showColumns() { hidden.clear(); }
void addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column) {
relations_src << RelationSrc(this_column, other_table, other_key, other_column);
updateRelations();
}
void removeRelations() {
relations_src.clear();
updateRelations();
}
void addTranslation(const QString & file);
void setConnectionName(const QString &conn_name) {connection_name = conn_name;}
QString connectionName() const {return connection_name;}
void setConnectionName(const QString & conn_name) { connection_name = conn_name; }
QString connectionName() const { return connection_name; }
QString getValuesQuery() const;
QString getUpdateQuery() const;
bool isEmpty() const;
QWidget * valueWidget(const QString & name) const {foreach (QWidget * w, cws) if (w->objectName() == name) return w; return 0;}
QWidget * valueWidget(const QString & name) const {
foreach(QWidget * w, cws)
if (w->objectName() == name) return w;
return 0;
}
void updateRelations();
protected:
QPair<QString, QString> trColumn(const QString & n) {QPair<QString, QString> trn = translates.value(n); if (trn.first.isEmpty()) return QPair<QString, QString>(n, ""); return trn;}
QPair<QString, QString> trColumn(const QString & n) {
QPair<QString, QString> trn = translates.value(n);
if (trn.first.isEmpty()) return QPair<QString, QString>(n, "");
return trn;
}
void createWidgets(const QSqlRecord & q);
void updateWidgets();
QVariant::Type fieldType(const QSqlField & f);
struct QAD_SQL_TABLE_EXPORT RelationSrc {
RelationSrc(const QString & v0 = QString(), const QString & v1 = QString(), const QString & v2 = QString(), const QString & v3 = QString()):
tcol(v0),
table(v1),
key(v2),
ocol(v3)
{}
RelationSrc(const QString & v0 = QString(),
const QString & v1 = QString(),
const QString & v2 = QString(),
const QString & v3 = QString())
: tcol(v0)
, table(v1)
, key(v2)
, ocol(v3) {}
QString tcol;
QString table;
QString key;
QString ocol;
};
QMap<QString, QPair<QString, QString> > translates;
QMap<QString, QPair<QString, QString>> translates;
QVector<RelationSrc> relations_src;
QMap<QString, QList<QPair<int, QString> > > relations;
QMap<QString, QList<QPair<int, QString>>> relations;
QMap<QString, QString> ftypes;
QSet<QString> hidden;
QWidgetList cws;
@@ -89,7 +113,6 @@ protected:
signals:
void updateRequest();
void widgetsCreated();
};
#endif // SQL_RECORD_WIDGET_H

View File

@@ -1,29 +1,37 @@
#include "sql_table_widget.h"
#include "qad_types.h"
#include "ui_sql_table_widget.h"
#include <QApplication>
#include <QFile>
#include <QTextStream>
#include <QFileInfo>
#include <QItemDelegate>
#include <QApplication>
#include "qad_types.h"
#include <QTextStream>
QString SQLTableWidget::_dir;
ColumnProperties::ColumnProperties(const QString & table_, const QString & type_, const QString & name_, const QString & def_, bool auto_, bool prim_, bool option_) {
visible = true;
table = table_;
name = name_;
def = def_;
ColumnProperties::ColumnProperties(const QString & table_,
const QString & type_,
const QString & name_,
const QString & def_,
bool auto_,
bool prim_,
bool option_) {
visible = true;
table = table_;
name = name_;
def = def_;
auto_increment = auto_;
primary = prim_;
optional = option_;
primary = prim_;
optional = option_;
int bs = type_.indexOf("("), bf = type_.indexOf(")");
size = type_.mid(bs + 1, bf - bs - 1).toInt();
size = type_.mid(bs + 1, bf - bs - 1).toInt();
key_column = 0;
type = typeFromString(type_.toLower());
is_text = (type == ColumnProperties::Chars || type == ColumnProperties::Text);
type = typeFromString(type_.toLower());
is_text = (type == ColumnProperties::Chars || type == ColumnProperties::Text);
}
@@ -33,19 +41,17 @@ ColumnProperties::DataType ColumnProperties::typeFromString(const QString & n) {
if (n.indexOf("time") >= 0) return ColumnProperties::Time;
if (n.indexOf("int") >= 0) return ColumnProperties::Int;
if (n.indexOf("char") >= 0) return ColumnProperties::Chars;
if (n.indexOf("dec") >= 0 || n.indexOf("numeric") >= 0 || n.indexOf("real") >= 0 ||
n.indexOf("float") >= 0 || n.indexOf("double") >= 0) return ColumnProperties::Float;
if (n.indexOf("dec") >= 0 || n.indexOf("numeric") >= 0 || n.indexOf("real") >= 0 || n.indexOf("float") >= 0 || n.indexOf("double") >= 0)
return ColumnProperties::Float;
if (n.indexOf("text") >= 0) return ColumnProperties::Text;
if (n.indexOf("blob") >= 0) return ColumnProperties::Binary;
return ColumnProperties::Unknown;
}
QVariant SQLQueryModel::data(const QModelIndex & item, int role) const {
QVariant var = QSqlQueryModel::data(item, role);
//QVariant::Type t = var.type();
// QVariant::Type t = var.type();
/*if (t == QVariant::Date) return var.toDate().toString("dd.MM.yyyy");
if (t == QVariant::Time) return var.toTime().toString("hh:mm:ss");
if (t == QVariant::DateTime) return var.toDateTime().toString("dd.MM.yyyy hh:mm:ss");*/
@@ -53,25 +59,23 @@ QVariant SQLQueryModel::data(const QModelIndex & item, int role) const {
}
bool SQLQueryModel::setData(const QModelIndex& index, const QVariant & value, int role) {
bool SQLQueryModel::setData(const QModelIndex & index, const QVariant & value, int role) {
if (value.isValid() && role == Qt::EditRole) {
QSqlQuery q(QSqlDatabase::database(conn_name));
int col = mapColumn(index.column());
int col = mapColumn(index.column());
ColumnProperties::DataType t = column_props[col].type;
bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text ||
t == ColumnProperties::Date || t == ColumnProperties::Time ||
t == ColumnProperties::ColumnProperties::DateTime);
QString val = value.toString();
bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text || t == ColumnProperties::Date ||
t == ColumnProperties::Time || t == ColumnProperties::ColumnProperties::DateTime);
QString val = value.toString();
if (t == ColumnProperties::Date) val = value.toDate().toString("yyyy-MM-dd");
if (t == ColumnProperties::Time) val = value.toTime().toString("hh:mm:ss");
if (t == ColumnProperties::DateTime) val = value.toDateTime().toString("yyyy-MM-dd hh:mm:ss");
if (!q.exec("UPDATE " + table_ + " SET " + column_props[col].name + "=" +
(quotes ? "'" : "") + val + (quotes ? "'" : "") +
" WHERE " + column_props[0].name + "=" + record(index.row()).value(0).toString() + ";")) {
if (!q.exec("UPDATE " + table_ + " SET " + column_props[col].name + "=" + (quotes ? "'" : "") + val + (quotes ? "'" : "") +
" WHERE " + column_props[0].name + "=" + record(index.row()).value(0).toString() + ";")) {
qDebug() << "[UPDATE]" << q.lastQuery() << "Error:" << q.lastError();
return false;
}
//qDebug() << "[UPDATE]" << q.lastQuery();
// qDebug() << "[UPDATE]" << q.lastQuery();
dataChanged(index, index);
updateTable(true);
emit tableChanged();
@@ -81,19 +85,34 @@ bool SQLQueryModel::setData(const QModelIndex& index, const QVariant & value, in
}
SQLUniEdit::SQLUniEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent): QWidget(parent), prop_(prop), connection_name(conn_name) {
wtext = 0; wint = 0; wfloat = 0; wdate = 0; wtime = 0; wdatetime = 0; wrelation = 0;
SQLUniEdit::SQLUniEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent)
: QWidget(parent)
, prop_(prop)
, connection_name(conn_name) {
wtext = 0;
wint = 0;
wfloat = 0;
wdate = 0;
wtime = 0;
wdatetime = 0;
wrelation = 0;
setProp(prop_);
w_ << (QWidget **)&wtext << (QWidget **)&wint << (QWidget **)&wfloat << (QWidget **)&wdate << (QWidget **)&wtime << (QWidget **)&wdatetime << (QWidget **)&wrelation;
w_ << (QWidget **)&wtext << (QWidget **)&wint << (QWidget **)&wfloat << (QWidget **)&wdate << (QWidget **)&wtime
<< (QWidget **)&wdatetime << (QWidget **)&wrelation;
}
void SQLUniEdit::setProp(const ColumnProperties & p) {
for (int i = 0; i < w_.size(); ++i) deleteW(*w_[i]);
wtext = 0; wint = 0; wfloat = 0; wdate = 0; wtime = 0; wdatetime = 0; wrelation = 0;
prop_ = p;
for (int i = 0; i < w_.size(); ++i)
deleteW(*w_[i]);
wtext = 0;
wint = 0;
wfloat = 0;
wdate = 0;
wtime = 0;
wdatetime = 0;
wrelation = 0;
prop_ = p;
if (prop_.isRelation()) {
wrelation = new QComboBox(this);
wrelation->installEventFilter(this);
@@ -103,15 +122,44 @@ void SQLUniEdit::setProp(const ColumnProperties & p) {
} else {
ColumnProperties::DataType t = prop_.getType();
switch (t) {
case ColumnProperties::Int: wint = new QSpinBox(this); wint->setRange(-0x7FFFFFFF, 0x7FFFFFFF); connect(wint, SIGNAL(valueChanged(int)), this, SLOT(value_int(int))); break;
case ColumnProperties::Float: wfloat = new QDoubleSpinBox(this); wfloat->setRange(-1E+300, 1E+300); wfloat->setDecimals(2); connect(wfloat, SIGNAL(valueChanged(double)), this, SLOT(value_float(double))); break;
case ColumnProperties::Date: wdate = new QDateEdit(this); wdate->setDisplayFormat("dd.MM.yyyy"); wdate->setCalendarPopup(true); wdate->setDate(QDate::currentDate()); connect(wdate, SIGNAL(dateChanged(QDate)), this, SLOT(value_date(QDate))); break;
case ColumnProperties::Time: wtime = new QTimeEdit(this); wtime->setDisplayFormat("hh:mm:ss"); wtime->setTime(QTime::currentTime()); connect(wtime, SIGNAL(timeChanged(QTime)), this, SLOT(value_time(QTime))); break;
case ColumnProperties::DateTime: wdatetime = new QDateTimeEdit(this); wdatetime->setDisplayFormat("dd.MM.yyyy hh:mm:ss"); wdatetime->setCalendarPopup(true); wdatetime->setDateTime(QDateTime::currentDateTime()); connect(wdatetime, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(value_datetime(QDateTime))); break;
case ColumnProperties::Int:
wint = new QSpinBox(this);
wint->setRange(-0x7FFFFFFF, 0x7FFFFFFF);
connect(wint, SIGNAL(valueChanged(int)), this, SLOT(value_int(int)));
break;
case ColumnProperties::Float:
wfloat = new QDoubleSpinBox(this);
wfloat->setRange(-1E+300, 1E+300);
wfloat->setDecimals(2);
connect(wfloat, SIGNAL(valueChanged(double)), this, SLOT(value_float(double)));
break;
case ColumnProperties::Date:
wdate = new QDateEdit(this);
wdate->setDisplayFormat("dd.MM.yyyy");
wdate->setCalendarPopup(true);
wdate->setDate(QDate::currentDate());
connect(wdate, SIGNAL(dateChanged(QDate)), this, SLOT(value_date(QDate)));
break;
case ColumnProperties::Time:
wtime = new QTimeEdit(this);
wtime->setDisplayFormat("hh:mm:ss");
wtime->setTime(QTime::currentTime());
connect(wtime, SIGNAL(timeChanged(QTime)), this, SLOT(value_time(QTime)));
break;
case ColumnProperties::DateTime:
wdatetime = new QDateTimeEdit(this);
wdatetime->setDisplayFormat("dd.MM.yyyy hh:mm:ss");
wdatetime->setCalendarPopup(true);
wdatetime->setDateTime(QDateTime::currentDateTime());
connect(wdatetime, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(value_datetime(QDateTime)));
break;
case ColumnProperties::Chars:
case ColumnProperties::Text:
case ColumnProperties::Unknown:
default: wtext = new QLineEdit(this); connect(wtext, SIGNAL(textChanged(QString)), this, SLOT(value_text(QString))); break;
default:
wtext = new QLineEdit(this);
connect(wtext, SIGNAL(textChanged(QString)), this, SLOT(value_text(QString)));
break;
}
}
for (int i = 0; i < w_.size(); ++i)
@@ -123,9 +171,8 @@ void SQLUniEdit::setProp(const ColumnProperties & p) {
QString SQLUniEdit::value(bool for_insert) {
QString ret;
ColumnProperties::DataType t = (for_insert ? prop_.type : prop_.getType());
bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text ||
t == ColumnProperties::Date || t == ColumnProperties::Time ||
t == ColumnProperties::ColumnProperties::DateTime);
bool quotes = (t == ColumnProperties::Chars || t == ColumnProperties::Text || t == ColumnProperties::Date ||
t == ColumnProperties::Time || t == ColumnProperties::ColumnProperties::DateTime);
if (quotes) ret = "'";
if (prop_.isRelation())
if (for_insert)
@@ -133,15 +180,20 @@ QString SQLUniEdit::value(bool for_insert) {
else
ret += wrelation->currentText();
else {
if (wint != 0) ret += QString::number(wint->value());
if (wint != 0)
ret += QString::number(wint->value());
else {
if (wfloat != 0) ret += QString::number(wfloat->value());
if (wfloat != 0)
ret += QString::number(wfloat->value());
else {
if (wdate != 0) ret += wdate->date().toString("yyyy-MM-dd");
if (wdate != 0)
ret += wdate->date().toString("yyyy-MM-dd");
else {
if (wtime != 0) ret += wtime->time().toString("hh:mm:ss");
if (wtime != 0)
ret += wtime->time().toString("hh:mm:ss");
else {
if (wdatetime != 0) ret += wdatetime->dateTime().toString("yyyy-MM-dd hh:mm:ss");
if (wdatetime != 0)
ret += wdatetime->dateTime().toString("yyyy-MM-dd hh:mm:ss");
else {
ret += wtext->text();
}
@@ -157,23 +209,27 @@ QString SQLUniEdit::value(bool for_insert) {
bool SQLUniEdit::eventFilter(QObject * o, QEvent * e) {
if (e->type() == QEvent::MouseButtonPress)
updateRelation();
if (e->type() == QEvent::MouseButtonPress) updateRelation();
return QWidget::eventFilter(o, e);
}
void SQLUniEdit::setValue(const QVariant & value) {
if (prop_.isRelation()) return;
if (wint != 0) wint->setValue(value.toInt());
if (wint != 0)
wint->setValue(value.toInt());
else {
if (wfloat != 0) wfloat->setValue(value.toDouble());
if (wfloat != 0)
wfloat->setValue(value.toDouble());
else {
if (wdate != 0) wdate->setDate(value.toDate());
if (wdate != 0)
wdate->setDate(value.toDate());
else {
if (wtime != 0) wtime->setTime(value.toTime());
if (wtime != 0)
wtime->setTime(value.toTime());
else {
if (wdatetime != 0) wdatetime->setDateTime(value.toDateTime());
if (wdatetime != 0)
wdatetime->setDateTime(value.toDateTime());
else {
wtext->setText(value.toString());
}
@@ -181,13 +237,12 @@ void SQLUniEdit::setValue(const QVariant & value) {
}
}
}
}
void SQLUniEdit::updateRelation() {
prop_.relation_list = SQLTableWidget::getColumnValues(prop_.relation_table, prop_.relation_key, prop_.relation_column, connection_name);
int pi = wrelation->currentIndex();
int pi = wrelation->currentIndex();
wrelation->blockSignals(true);
wrelation->clear();
for (int i = 0; i < prop_.relation_list.size(); ++i)
@@ -197,7 +252,6 @@ void SQLUniEdit::updateRelation() {
}
SQLNewEdit::SQLNewEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent): QWidget(parent), prop_(prop) {
line = new SQLUniEdit(prop, conn_name);
line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
@@ -224,14 +278,14 @@ void SQLNewEdit::setProp(const ColumnProperties & p) {
}
SQLFilterEdit::SQLFilterEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent): QWidget(parent), prop_(prop) {
line = new SQLUniEdit(prop, conn_name);
line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
combo = new QComboBox();
combo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QStringList sl;
sl << " " << "=" << QString::fromUtf8("") << QString::fromUtf8("") << ">" << QString::fromUtf8("") << "<" << QString::fromUtf8("");
sl << " "
<< "=" << QString::fromUtf8("") << QString::fromUtf8("") << ">" << QString::fromUtf8("") << "<" << QString::fromUtf8("");
combo->addItems(sl);
combo->setCurrentIndex(0);
connect(line, SIGNAL(valueChanged(QVariant)), this, SIGNAL(filterChanged()));
@@ -275,14 +329,17 @@ QString SQLFilterEdit::filter() const {
void SQLFilterEdit::clear() {
line->setValue(QVariant());
combo->setCurrentIndex(0);
}
SQLItemDelegate::SQLItemDelegate(QList<ColumnProperties> & cp, QVector<int> & ci, bool & ro, const QString & conn_name, QObject * parent):
QStyledItemDelegate(parent), column_props(cp), column_indexes(ci), read_only(ro), connection_name(conn_name) {;}
SQLItemDelegate::SQLItemDelegate(QList<ColumnProperties> & cp, QVector<int> & ci, bool & ro, const QString & conn_name, QObject * parent)
: QStyledItemDelegate(parent)
, column_props(cp)
, column_indexes(ci)
, read_only(ro)
, connection_name(conn_name) {
;
}
QWidget * SQLItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const {
@@ -290,19 +347,24 @@ QWidget * SQLItemDelegate::createEditor(QWidget * parent, const QStyleOptionView
ColumnProperties & cp(column_props[mapColumn(index.column())]);
if (cp.isRelation()) {
cp.relation_list = SQLTableWidget::getColumnValues(cp.relation_table, cp.relation_key, cp.relation_column, connection_name);
QComboBox * w = new QComboBox(parent);
QComboBox * w = new QComboBox(parent);
w->setGeometry(option.rect);
for (int i = 0; i < cp.relation_list.size(); ++i) {
w->addItem(cp.relation_list[i].second, cp.relation_list[i].first);
if (index.data().toString() == cp.relation_list[i].second)
w->setCurrentIndex(i);
if (index.data().toString() == cp.relation_list[i].second) w->setCurrentIndex(i);
}
return w;
} else {
QWidget * w = QStyledItemDelegate::createEditor(parent, option, index);
if (qobject_cast<QTimeEdit * >(w)) {qobject_cast<QTimeEdit * >(w)->setDisplayFormat("hh:mm:ss");}
else if (qobject_cast<QDateEdit * >(w)) {qobject_cast<QDateEdit * >(w)->setCalendarPopup(true); qobject_cast<QDateEdit * >(w)->setDisplayFormat("dd.MM.yyyy");}
else if (qobject_cast<QDateTimeEdit * >(w)) {qobject_cast<QDateTimeEdit * >(w)->setCalendarPopup(true); qobject_cast<QDateTimeEdit * >(w)->setDisplayFormat("dd.MM.yyyy hh:mm:ss");}
if (qobject_cast<QTimeEdit *>(w)) {
qobject_cast<QTimeEdit *>(w)->setDisplayFormat("hh:mm:ss");
} else if (qobject_cast<QDateEdit *>(w)) {
qobject_cast<QDateEdit *>(w)->setCalendarPopup(true);
qobject_cast<QDateEdit *>(w)->setDisplayFormat("dd.MM.yyyy");
} else if (qobject_cast<QDateTimeEdit *>(w)) {
qobject_cast<QDateTimeEdit *>(w)->setCalendarPopup(true);
qobject_cast<QDateTimeEdit *>(w)->setDisplayFormat("dd.MM.yyyy hh:mm:ss");
}
return w;
}
return 0;
@@ -319,20 +381,19 @@ QString SQLItemDelegate::displayText(const QVariant & value, const QLocale & loc
void SQLItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const {
if (qobject_cast<QComboBox * >(editor)) {
model->setData(index, qobject_cast<QComboBox * >(editor)->itemData(qobject_cast<QComboBox * >(editor)->currentIndex()));
if (qobject_cast<QComboBox *>(editor)) {
model->setData(index, qobject_cast<QComboBox *>(editor)->itemData(qobject_cast<QComboBox *>(editor)->currentIndex()));
return;
}
QStyledItemDelegate::setModelData(editor, model, index);
}
SQLTableWidget::SQLTableWidget(QWidget * parent): QWidget(parent), filters_group(this) {
ui = new Ui::SQLTableWidget();
ui->setupUi(this);
model = 0;
timer = 0;
model = 0;
timer = 0;
connection_name = QSqlDatabase::defaultConnection;
filters_active = first_update = debug = true;
table_opened = read_only = false;
@@ -345,30 +406,33 @@ SQLTableWidget::SQLTableWidget(QWidget * parent): QWidget(parent), filters_group
ui->view->setItemDelegate(new SQLItemDelegate(column_props, column_indexes, read_only, connection_name));
ui->view->horizontalHeader()->setItemDelegate(new QItemDelegate());
ui->view->verticalHeader()->setDefaultSectionSize(fontHeight(this) * 1.5);
//qDebug() << view->horizontalHeader()->itemDelegate();
//qDebug() << fontMetrics().elidedText(, Qt::ElideNone, 30, Qt::TextWordWrap);
// qDebug() << view->horizontalHeader()->itemDelegate();
// qDebug() << fontMetrics().elidedText(, Qt::ElideNone, 30, Qt::TextWordWrap);
setTableVisible(false);
connect(ui->view->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(header_sectionResized(int, int, int)));
connect(ui->view->horizontalHeader(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(header_sortIndicatorChanged(int, Qt::SortOrder)));
connect(ui->view->horizontalHeader(),
SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)),
this,
SLOT(header_sortIndicatorChanged(int, Qt::SortOrder)));
connect(ui->view->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scrolled(int)));
//act_add.setText(tr("Add ..."));
//act_del.setText(tr("Remove selected"));
// act_add.setText(tr("Add ..."));
// act_del.setText(tr("Remove selected"));
action_del = new QAction(QIcon(":/icons/edit-delete.png"), tr("Remove selected"), this);
connect(action_del, SIGNAL(triggered(bool)), this, SLOT(del_triggered()));
popup_menu.addAction(action_del);
ui->actionFilter_AND->setChecked(true);
filters_group.addAction(ui->actionFilter_AND);
filters_group.addAction(ui->actionFilter_OR);
connect(&filters_group, SIGNAL(triggered(QAction * )), this, SLOT(updateTable()));
connect(&filters_group, SIGNAL(triggered(QAction *)), this, SLOT(updateTable()));
popup_filter.addAction(ui->actionFiltersClear);
popup_filter.addSeparator();
popup_filter.addAction(ui->actionFilter_AND);
popup_filter.addAction(ui->actionFilter_OR);
ui->buttonFilterConfig->setMenu(&popup_filter);
//connect(&act_add, SIGNAL(triggered(bool)), this, SLOT(add_triggered()));
//connect(&act_del, SIGNAL(triggered(bool)), this, SLOT(del_triggered()));
// connect(&act_add, SIGNAL(triggered(bool)), this, SLOT(add_triggered()));
// connect(&act_del, SIGNAL(triggered(bool)), this, SLOT(del_triggered()));
}
@@ -381,14 +445,20 @@ SQLTableWidget::~SQLTableWidget() {
bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) {
if (o == ui->view) {
if (e->type() == QEvent::KeyPress) {
QKeyEvent * ke = (QKeyEvent * )e;
if (ke->key() == Qt::Key_Home) {ui->view->selectRow(0); return true;}
if (ke->key() == Qt::Key_End) {ui->view->selectRow(ui->view->verticalHeader()->count() - 1); return true;}
QKeyEvent * ke = (QKeyEvent *)e;
if (ke->key() == Qt::Key_Home) {
ui->view->selectRow(0);
return true;
}
if (ke->key() == Qt::Key_End) {
ui->view->selectRow(ui->view->verticalHeader()->count() - 1);
return true;
}
}
}
if (o == ui->view->viewport()) {
if (e->type() == QEvent::MouseButtonPress) {
QMouseEvent * me = (QMouseEvent * )e;
QMouseEvent * me = (QMouseEvent *)e;
if (me->button() == Qt::RightButton) {
action_del->setVisible(!read_only);
popup_menu.popup(me->globalPos());
@@ -396,24 +466,24 @@ bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) {
}
}
if (o == ui->view->horizontalHeader()->viewport()) {
QMouseEvent * me = (QMouseEvent * )e;
if (e->type() == QEvent::MouseButtonPress)
pp = me->pos();
QMouseEvent * me = (QMouseEvent *)e;
if (e->type() == QEvent::MouseButtonPress) pp = me->pos();
if (e->type() == QEvent::MouseButtonRelease) {
if ((me->pos() - pp).manhattanLength() < QApplication::startDragDistance()) {
if (me->button() == Qt::LeftButton) {
int ci = ui->view->horizontalHeader()->logicalIndexAt(me->pos()),
ri = ui->view->horizontalHeader()->logicalIndexAt(me->pos() + QPoint(3, 0)),
li = ui->view->horizontalHeader()->logicalIndexAt(me->pos() - QPoint(3, 0));
//qDebug() << ci << ri << li;
if ((ci < 0) || (ci >= ui->view->horizontalHeader()->count()) || (ci != ri) || (ci != li) || (tm.elapsed() <= QApplication::doubleClickInterval())) {
ri = ui->view->horizontalHeader()->logicalIndexAt(me->pos() + QPoint(3, 0)),
li = ui->view->horizontalHeader()->logicalIndexAt(me->pos() - QPoint(3, 0));
// qDebug() << ci << ri << li;
if ((ci < 0) || (ci >= ui->view->horizontalHeader()->count()) || (ci != ri) || (ci != li) ||
(tm.elapsed() <= QApplication::doubleClickInterval())) {
tm.restart();
return QObject::eventFilter(o, e);
}
tm.restart();
Qt::SortOrder o = Qt::AscendingOrder;
if (ui->view->horizontalHeader()->sortIndicatorSection() == ci &&
ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::AscendingOrder)
ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::AscendingOrder)
o = Qt::DescendingOrder;
ui->view->horizontalHeader()->setSortIndicator(ci, o);
return true;
@@ -422,7 +492,7 @@ bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) {
popup_col.clear();
for (int i = 0; i < column_props.size(); ++i) {
QPair<QString, QString> ctr = trColumn(column_props[i].name);
QAction * a = popup_col.addAction(ctr.first, this, SLOT(column_triggered(bool)));
QAction * a = popup_col.addAction(ctr.first, this, SLOT(column_triggered(bool)));
a->setToolTip(ctr.second);
a->setCheckable(true);
a->setChecked(column_props[i].visible);
@@ -431,14 +501,15 @@ bool SQLTableWidget::eventFilter(QObject * o, QEvent * e) {
popup_col.popup(me->globalPos());
return true;
}
} else return true;
} else
return true;
}
}
return QWidget::eventFilter(o, e);
}
void SQLTableWidget::timerEvent(QTimerEvent * ) {
void SQLTableWidget::timerEvent(QTimerEvent *) {
setTableName(table_);
}
@@ -446,12 +517,11 @@ void SQLTableWidget::timerEvent(QTimerEvent * ) {
void SQLTableWidget::changeEvent(QEvent * e) {
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
action_del->setText(tr("Remove selected"));
break;
default:
break;
case QEvent::LanguageChange:
ui->retranslateUi(this);
action_del->setText(tr("Remove selected"));
break;
default: break;
}
}
@@ -461,7 +531,7 @@ void SQLTableWidget::setTableName(const QString & t) {
stopTimer();
table_opened = false;
first_update = true;
table_ = t;
table_ = t;
if (!QSqlDatabase::database(connection_name).isOpen()) {
if (debug) qDebug() << "[setTableName] Database in not opened!";
setTableVisible(false);
@@ -471,15 +541,19 @@ void SQLTableWidget::setTableName(const QString & t) {
model = new SQLQueryModel(table_, connection_name, column_props, column_indexes, this);
connect(model, SIGNAL(updateTable(bool)), this, SLOT(updateTable(bool)));
connect(model, SIGNAL(tableChanged()), this, SIGNAL(tableChanged()));
//model->setTable(table_);
// model->setTable(table_);
cquery = "SELECT * FROM " + table_ + ";";
model->setQuery(cquery, QSqlDatabase::database(connection_name));
ui->view->setModel(model);
connect(ui->view->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SIGNAL(selectionChanged()), Qt::UniqueConnection);
connect(ui->view->selectionModel(),
SIGNAL(currentRowChanged(QModelIndex, QModelIndex)),
this,
SIGNAL(selectionChanged()),
Qt::UniqueConnection);
//((QSqlQueryModel * )model)->setQuery(QSqlQuery("SELECT id FROM " + table_ + ";"));
setTableVisible(checkTable());
updateTable();
foreach (const QString & wr, wait_rels) {
foreach(const QString & wr, wait_rels) {
QStringList wrl = wr.split(";");
addRelation(wrl[0], wrl[1], wrl[2], wrl[3]);
}
@@ -492,59 +566,58 @@ void SQLTableWidget::setTableName(const QString & t) {
bool SQLTableWidget::checkTable() {
table_opened = false;
table_opened = false;
QSqlDatabase db = QSqlDatabase::database(connection_name);
if (db.driver() == 0) return false;
bool te = db.tables(QSql::Tables).contains(table_, Qt::CaseInsensitive );
//qDebug() << "tables:" << db.tables(QSql::Tables) << table_ << table_opened;
bool te = db.tables(QSql::Tables).contains(table_, Qt::CaseInsensitive);
// qDebug() << "tables:" << db.tables(QSql::Tables) << table_ << table_opened;
if (!te) {
timer = startTimer(1000);
return false;
}
/*if (!q.exec("SHOW TABLES")) {
qDebug() << "[SHOW TABLES]" << q.lastError();
timer = startTimer(1000);
return false;
qDebug() << "[SHOW TABLES]" << q.lastError();
timer = startTimer(1000);
return false;
}
while (q.next()) {
//qDebug() << q.value(0);
if (q.value(0) == table_)
{table_opened = true; break;}
//qDebug() << q.value(0);
if (q.value(0) == table_)
{table_opened = true; break;}
}
if (!table_opened) {
timer = startTimer(1000);
return false;
timer = startTimer(1000);
return false;
}*/
QSqlRecord header = db.record(table_);
QString pin = db.primaryIndex(table_).fieldName(0);
table_opened = true;
QString pin = db.primaryIndex(table_).fieldName(0);
table_opened = true;
column_props.clear();
for (int i = 0; i < header.count(); ++i) {
QSqlField f = header.field(i);
column_props << ColumnProperties(table_,
f.type() == QVariant::String ? "text" : QVariant::typeToName(f.type()),
f.name(),
f.defaultValue().toString(),
f.isAutoValue(),
f.name() == pin,
f.requiredStatus() == QSqlField::Optional
);
f.type() == QVariant::String ? "text" : QVariant::typeToName(f.type()),
f.name(),
f.defaultValue().toString(),
f.isAutoValue(),
f.name() == pin,
f.requiredStatus() == QSqlField::Optional);
}
/*if (!q.exec("DESCRIBE " + table_ + ";")) {
qDebug() << "[DESCRIBE " + table_ + "]" << q.lastError();
timer = startTimer(1000);
return false;
qDebug() << "[DESCRIBE " + table_ + "]" << q.lastError();
timer = startTimer(1000);
return false;
}
while (q.next()) {
column_props << ColumnProperties(table_,
q.value(1).toString().toLower(),
q.value(0).toString().toLower(),
q.value(4).toString().toLower(),
q.value(5).toString().toLower().indexOf("auto_increment") >= 0,
q.value(3).toString().toLower().indexOf("pri") >= 0);
column_props << ColumnProperties(table_,
q.value(1).toString().toLower(),
q.value(0).toString().toLower(),
q.value(4).toString().toLower(),
q.value(5).toString().toLower().indexOf("auto_increment") >= 0,
q.value(3).toString().toLower().indexOf("pri") >= 0);
}*/
//ui->labelNew->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
//ui->labelFilter->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
// ui->labelNew->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
// ui->labelFilter->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
ui->scrollAreaNew->setFixedHeight(QLineEdit().sizeHint().height() + 2);
ui->scrollAreaFilter->setFixedHeight(QLineEdit().sizeHint().height() + 2);
qDeleteAll(column_news);
@@ -571,7 +644,7 @@ bool SQLTableWidget::checkTable() {
QStringList SQLTableWidget::getTableColumns(const QString & t) {
QStringList ret;
QSqlDatabase db = QSqlDatabase::database(connection_name);
QSqlDatabase db = QSqlDatabase::database(connection_name);
QSqlRecord header = db.record(t);
for (int i = 0; i < header.count(); ++i)
ret << header.field(i).name();
@@ -580,7 +653,7 @@ QStringList SQLTableWidget::getTableColumns(const QString & t) {
QString SQLTableWidget::getColumnType(const QString & t, const QString & c) {
QSqlDatabase db = QSqlDatabase::database(connection_name);
QSqlDatabase db = QSqlDatabase::database(connection_name);
QSqlRecord header = db.record(t);
for (int i = 0; i < header.count(); ++i) {
QSqlField f = header.field(i);
@@ -591,11 +664,11 @@ QString SQLTableWidget::getColumnType(const QString & t, const QString & c) {
}
QList<QPair<QString, QString> > SQLTableWidget::getColumnValues(const QString &t, const QString &k, const QString &c, const QString &conn_name) {
QList<QPair<QString, QString> > ret;
QList<QPair<QString, QString>>
SQLTableWidget::getColumnValues(const QString & t, const QString & k, const QString & c, const QString & conn_name) {
QList<QPair<QString, QString>> ret;
QSqlQuery q(QSqlDatabase::database(conn_name));
if (!q.exec("SELECT " + t + "." + k + "," + t + "." + c + " FROM " + t + ";"))
return ret;
if (!q.exec("SELECT " + t + "." + k + "," + t + "." + c + " FROM " + t + ";")) return ret;
while (q.next())
ret << QPair<QString, QString>(q.value(0).toString(), q.value(1).toString());
return ret;
@@ -604,8 +677,7 @@ QList<QPair<QString, QString> > SQLTableWidget::getColumnValues(const QString &t
QPair<QString, QString> SQLTableWidget::trColumn(const QString & n) {
QPair<QString, QString> ftr = fixed_translates.value(n);
if (!ftr.first.isEmpty())
return ftr;
if (!ftr.first.isEmpty()) return ftr;
QPair<QString, QString> trn = translates.value(n);
if (trn.first.isEmpty()) return QPair<QString, QString>(n, "");
return trn;
@@ -616,42 +688,39 @@ void SQLTableWidget::updateTable(bool save_selection) {
if (!filters_active || !table_opened) return;
int vp = ui->view->verticalScrollBar()->value();
int hp = ui->view->horizontalScrollBar()->value();
//bool focus = view->hasFocus();
// bool focus = view->hasFocus();
QModelIndex csi;
QModelIndexList sl;
if (save_selection) {
csi = ui->view->selectionModel()->currentIndex();
sl = ui->view->selectionModel()->selectedRows();
sl = ui->view->selectionModel()->selectedRows();
}
if (custom_query.isEmpty()) {
QString cr = columnRelations(), cf = columnFilters();
bool where = !cr.isEmpty() || !cf.isEmpty(), and_ = !cr.isEmpty() && !cf.isEmpty();
cquery = "SELECT " + columnNames() + " FROM " + tableNames() +
(where ? " WHERE " : "") + cr + (and_ ? " AND " : "") + cf + " ORDER BY " +
column_props[ui->view->horizontalHeader()->sortIndicatorSection()].fullName() +
(ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::DescendingOrder ? " DESC" : " ASC") + ";";
cquery = "SELECT " + columnNames() + " FROM " + tableNames() + (where ? " WHERE " : "") + cr + (and_ ? " AND " : "") + cf +
" ORDER BY " + column_props[ui->view->horizontalHeader()->sortIndicatorSection()].fullName() +
(ui->view->horizontalHeader()->sortIndicatorOrder() == Qt::DescendingOrder ? " DESC" : " ASC") + ";";
} else
cquery = custom_query;
//qDebug() << cquery;
// qDebug() << cquery;
model->setQuery(cquery, QSqlDatabase::database(connection_name));
if (model->lastError().isValid())
qDebug() << model->lastError();
if (model->lastError().isValid()) qDebug() << model->lastError();
if (first_update) {
ui->view->resizeColumnsToContents();
for (int i = 0; i < ui->view->horizontalHeader()->count(); ++i)
if (ui->view->horizontalHeader()->sectionSize(i) < 100)
ui->view->horizontalHeader()->resizeSection(i, 100);
if (ui->view->horizontalHeader()->sectionSize(i) < 100) ui->view->horizontalHeader()->resizeSection(i, 100);
first_update = false;
}
//ui->labelNew->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
//ui->labelFilter->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
// ui->labelNew->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
// ui->labelFilter->setFixedWidth(qMax<int>(ui->view->verticalHeader()->sizeHint().width() + 2, 16));
ui->layoutNew->invalidate();
if (save_selection) {
QItemSelectionModel * sm = ui->view->selectionModel();
foreach (const QModelIndex & i, sl)
foreach(const QModelIndex & i, sl)
sm->select(i, QItemSelectionModel::Select | QItemSelectionModel::Rows);
sm->setCurrentIndex(csi, QItemSelectionModel::Select);
//ui->view->setFocus();
// ui->view->setFocus();
}
if (custom_query.isEmpty()) {
for (int i = 0; i < model->columnCount(); ++i) {
@@ -663,7 +732,7 @@ void SQLTableWidget::updateTable(bool save_selection) {
if (custom_col_names.isEmpty()) {
QSqlRecord header = model->record();
for (int i = 0; i < header.count(); ++i) {
QSqlField f = header.field(i);
QSqlField f = header.field(i);
QPair<QString, QString> ctr = trColumn(f.name());
model->setHeaderData(i, Qt::Horizontal, ctr.first, Qt::DisplayRole);
model->setHeaderData(i, Qt::Horizontal, ctr.second, Qt::ToolTipRole);
@@ -678,7 +747,7 @@ void SQLTableWidget::updateTable(bool save_selection) {
}
ui->view->verticalScrollBar()->setValue(vp);
ui->view->horizontalScrollBar()->setValue(hp);
//if (focus) view->setFocus();
// if (focus) view->setFocus();
}
@@ -693,10 +762,8 @@ QString SQLTableWidget::tableNames() {
QSet<QString> rtables;
for (int i = 0; i < column_props.size(); ++i) {
ColumnProperties & cp(column_props[i]);
if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty())
continue;
if (rtables.contains(cp.relation_table))
continue;
if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty()) continue;
if (rtables.contains(cp.relation_table)) continue;
rtables << cp.relation_table;
ret.append("," + cp.relation_table);
}
@@ -712,14 +779,13 @@ QString SQLTableWidget::columnNames() {
ColumnProperties & cp(column_props[i]);
column_news[i]->setVisible(cp.visible);
column_filters[i]->setVisible(cp.visible);
if (!cp.visible && !cp.primary)
continue;
if (!cp.visible && !cp.primary) continue;
if (!first) ret.append(",");
first = false;
ret.append(cp.fullName());
if (i > 0) column_indexes.push_back(i);
}
//qDebug() << column_indexes;
// qDebug() << column_indexes;
return ret;
}
@@ -728,10 +794,8 @@ QString SQLTableWidget::columnFilters() {
QString ret;
bool and_ = ui->actionFilter_AND->isChecked();
for (int i = 0; i < column_props.size(); ++i) {
if (!column_filters[i]->isVisible() || column_filters[i]->isEmpty())
continue;
if (!ret.isEmpty())
ret.append(and_ ? " AND " : " OR ");
if (!column_filters[i]->isVisible() || column_filters[i]->isEmpty()) continue;
if (!ret.isEmpty()) ret.append(and_ ? " AND " : " OR ");
ret.append(column_filters[i]->filter());
}
if (!ret.isEmpty()) {
@@ -746,10 +810,8 @@ QString SQLTableWidget::columnRelations() {
QString ret;
for (int i = 0; i < column_props.size(); ++i) {
ColumnProperties & cp(column_props[i]);
if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty())
continue;
if (!ret.isEmpty())
ret.append(" AND ");
if (!cp.visible || cp.relation_key.isEmpty() || cp.relation_column.isEmpty()) continue;
if (!ret.isEmpty()) ret.append(" AND ");
ret.append(table_ + "." + cp.name + "=");
ret.append(cp.relation_table + "." + cp.relation_key);
}
@@ -792,13 +854,13 @@ void SQLTableWidget::on_buttonAdd_clicked() {
emit tableChanged();
} else
qDebug() << q.lastError();
//qDebug() << q.lastQuery();
// qDebug() << q.lastQuery();
}
void SQLTableWidget::on_actionFiltersClear_triggered() {
filters_active = false;
foreach (SQLFilterEdit * l, column_filters)
foreach(SQLFilterEdit * l, column_filters)
l->clear();
filters_active = true;
updateTable();
@@ -814,18 +876,18 @@ void SQLTableWidget::on_view_clicked(const QModelIndex & index) {
void SQLTableWidget::del_triggered() {
QModelIndexList si = ui->view->selectionModel()->selectedIndexes();
QSet<int> ids;
foreach (const QModelIndex & i, si)
foreach(const QModelIndex & i, si)
ids << model->index(i.row(), 0).data().toInt();
if (ids.isEmpty()) return;
QString qs("DELETE FROM " + table_ + " WHERE " + column_props[0].name + " IN (");
bool first = true;
foreach (int i, ids) {
foreach(int i, ids) {
if (!first) qs.append(",");
qs.append(QString::number(i));
first = false;
}
qs.append(");");
//qDebug() << qs; return;
// qDebug() << qs; return;
QSqlQuery q(QSqlDatabase::database(connection_name));
if (q.exec(qs)) {
updateTable();
@@ -842,7 +904,7 @@ void SQLTableWidget::setColumnVisible(int ind, bool visible) {
ui->view->setColumnHidden(0, !visible);
if (visible) ui->view->horizontalHeader()->resizeSection(0, ui->view->horizontalHeader()->defaultSectionSize());
}
//qDebug() << ind << on;
// qDebug() << ind << on;
updateTable();
for (int i = 0; i < ui->view->horizontalHeader()->count(); ++i) {
column_news[mapColumn(i)]->setFixedWidth(ui->view->horizontalHeader()->sectionSize(i));
@@ -851,16 +913,19 @@ void SQLTableWidget::setColumnVisible(int ind, bool visible) {
}
bool SQLTableWidget::addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column) {
bool SQLTableWidget::addRelation(const QString & this_column,
const QString & other_table,
const QString & other_key,
const QString & other_column) {
QString wr = this_column + ";" + other_table + ";" + other_key + ";" + other_column;
if (!wait_rels.contains(wr)) wait_rels << wr;
ColumnProperties * cp = const_cast<ColumnProperties * >(columnProperty(this_column));
ColumnProperties * cp = const_cast<ColumnProperties *>(columnProperty(this_column));
if (cp == 0) return false;
cp->relation_table = other_table;
cp->relation_key = other_key;
cp->relation_table = other_table;
cp->relation_key = other_key;
cp->relation_column = other_column;
cp->relation_type = ColumnProperties::typeFromString(getColumnType(other_table, other_column));
cp->relation_list = getColumnValues(other_table, other_key, other_column, connection_name);
cp->relation_type = ColumnProperties::typeFromString(getColumnType(other_table, other_column));
cp->relation_list = getColumnValues(other_table, other_key, other_column, connection_name);
for (int i = 0; i < column_props.size(); ++i)
column_news[i]->setProp(column_props[i]);
for (int i = 0; i < column_props.size(); ++i)
@@ -873,7 +938,7 @@ bool SQLTableWidget::addRelation(const QString & this_column, const QString & ot
void SQLTableWidget::addTranslation(const QString & file) {
QPIConfig conf(file, QIODevice::ReadOnly, QPIConfig::Config);
QPIConfig::Branch ae = conf.allLeaves();
foreach (QPIConfig::Entry * e, ae)
foreach(QPIConfig::Entry * e, ae)
translates[e->name()] = QPair<QString, QString>(e->value(), e->comment());
}
@@ -894,8 +959,8 @@ void SQLTableWidget::selectId(int id) {
}
void SQLTableWidget::setAdditionalActions(QList<QAction * > a) {
foreach (QAction * i, add_actions)
void SQLTableWidget::setAdditionalActions(QList<QAction *> a) {
foreach(QAction * i, add_actions)
popup_menu.removeAction(i);
add_actions = a;
popup_menu.addActions(a);
@@ -914,19 +979,17 @@ QString SQLTableWidget::preprocessScript(QString text) {
int ce = 0;
while (!s.atEnd()) {
QString line = s.readLine();
ce = line.indexOf("--");
if (ce >= 0)
line.chop(line.length() - ce);
ce = line.indexOf("--");
if (ce >= 0) line.chop(line.length() - ce);
out.append(line).append("\n");
}
int cs = out.indexOf("/*");
while (cs >= 0) {
ce = out.indexOf("*/", cs);
if (ce > cs)
out.remove(cs, ce - cs + 2);
if (ce > cs) out.remove(cs, ce - cs + 2);
cs = out.indexOf("/*");
}
//qDebug() << out;
// qDebug() << out;
return out;
}
@@ -951,8 +1014,7 @@ bool SQLTableWidget::executeScript(const QString & text_, QSqlDatabase db, bool
} else {
if (!q.exec(line)) {
qDebug() << q.lastError();
if (!skip_errors)
return false;
if (!skip_errors) return false;
}
}
ls = le + 1;
@@ -969,10 +1031,10 @@ bool SQLTableWidget::executeScriptFile(const QString & file, QSqlDatabase db, bo
qDebug() << "Can`t open file" << file << "!";
return false;
}
QString pd = _dir;
_dir = QFileInfo(f).absolutePath() + "/";
QString pd = _dir;
_dir = QFileInfo(f).absolutePath() + "/";
QByteArray ba = f.readAll();
bool ok = executeScript(QString::fromUtf8(ba.data(), ba.size()), db, skip_errors, sqlite);
bool ok = executeScript(QString::fromUtf8(ba.data(), ba.size()), db, skip_errors, sqlite);
f.close();
_dir = pd;
return ok;
@@ -980,7 +1042,7 @@ bool SQLTableWidget::executeScriptFile(const QString & file, QSqlDatabase db, bo
void SQLTableWidget::column_triggered(bool on) {
setColumnVisible(((QAction * )sender())->data().toInt(), on);
setColumnVisible(((QAction *)sender())->data().toInt(), on);
}
@@ -1017,27 +1079,26 @@ bool SQLTableWidget::connectToDatabase(const QString & config, const QString & c
}
}
}
if (!ok)
QSqlDatabase::removeDatabase(conn_name);
if (!ok) QSqlDatabase::removeDatabase(conn_name);
/*QSqlQuery q;
QString dbname = conf.getValue("database", "").stringValue();
bool dbex = false;
if (!q.exec("SHOW DATABASES;")) {
qDebug() << "[SHOW DATABASES]" << q.lastError();
return false;
qDebug() << "[SHOW DATABASES]" << q.lastError();
return false;
}
while (q.next())
if (q.value(0) == dbname)
{dbex = true; break;}
if (q.value(0) == dbname)
{dbex = true; break;}
if (!dbex) {
if (!q.exec("CREATE DATABASE " + dbname + ";")) {
qDebug() << "[CREATE DATABASE]" << q.lastError();
return false;
}
if (!q.exec("CREATE DATABASE " + dbname + ";")) {
qDebug() << "[CREATE DATABASE]" << q.lastError();
return false;
}
}
if (!q.exec("USE " + dbname + ";")) {
qDebug() << "[USE]" << q.lastError();
return false;
qDebug() << "[USE]" << q.lastError();
return false;
}*/
return ok;
}

View File

@@ -1,64 +1,90 @@
/*
QAD - Qt ADvanced
QAD - Qt ADvanced
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SQL_TABLE_WIDGET_H
#define SQL_TABLE_WIDGET_H
#include "qad_sql_table_export.h"
#include "qpiconfig.h"
#include <QAction>
#include <QActionGroup>
#include <QBoxLayout>
#include <QCheckBox>
#include <QComboBox>
#include <QDateTimeEdit>
#include <QDebug>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QMouseEvent>
#include <QScrollBar>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlField>
#include <QSqlIndex>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlTableModel>
#include <QSqlError>
#include <QSqlIndex>
#include <QBoxLayout>
#include <QTableView>
#include <QLabel>
#include <QToolButton>
#include <QAction>
#include <QMenu>
#include <QMouseEvent>
#include <QHeaderView>
#include <QLineEdit>
#include <QScrollBar>
#include <QDoubleSpinBox>
#include <QDateTimeEdit>
#include <QComboBox>
#include <QStyledItemDelegate>
#include <QCheckBox>
#include <QDebug>
#include <QElapsedTimer>
#include <QActionGroup>
#include "qpiconfig.h"
#include "qad_sql_table_export.h"
#include <QTableView>
#include <QToolButton>
struct QAD_SQL_TABLE_EXPORT ColumnProperties {
enum DataType {Unknown, Int, Float, Chars, Text, Binary, Date, Time, DateTime};
ColumnProperties(const QString & table_, const QString & type_, const QString & name_, const QString & def_, bool auto_, bool prim_, bool option_);
bool isRelation() const {return (!relation_key.isEmpty() && !relation_column.isEmpty());}
QString shortName() const {if (!isRelation()) return name; return relation_column;}
QString fullName() const {if (!isRelation()) return table + "." + name; return (relation_table.isEmpty() ? "" : relation_table + ".") + relation_column;}
DataType getType() const {if (!isRelation()) return type; return relation_type;}
enum DataType {
Unknown,
Int,
Float,
Chars,
Text,
Binary,
Date,
Time,
DateTime
};
ColumnProperties(const QString & table_,
const QString & type_,
const QString & name_,
const QString & def_,
bool auto_,
bool prim_,
bool option_);
bool isRelation() const { return (!relation_key.isEmpty() && !relation_column.isEmpty()); }
QString shortName() const {
if (!isRelation()) return name;
return relation_column;
}
QString fullName() const {
if (!isRelation()) return table + "." + name;
return (relation_table.isEmpty() ? "" : relation_table + ".") + relation_column;
}
DataType getType() const {
if (!isRelation()) return type;
return relation_type;
}
static DataType typeFromString(const QString & n);
DataType type;
int size;
bool auto_increment;
@@ -71,33 +97,44 @@ struct QAD_SQL_TABLE_EXPORT ColumnProperties {
QString relation_table;
QString relation_key;
QString relation_column;
QList<QPair<QString, QString> > relation_list; // <id, relation_column>
QList<QPair<QString, QString>> relation_list; // <id, relation_column>
DataType relation_type;
int key_column;
QString def;
};
struct QAD_SQL_TABLE_EXPORT TableColumns {
int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];}
int mapColumn(int abs_ind) const {
if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0;
return column_indexes[abs_ind - 1];
}
QVector<int> column_indexes;
QList<ColumnProperties> columns;
};
class QAD_SQL_TABLE_EXPORT SQLQueryModel: public QSqlQueryModel {
Q_OBJECT
public:
explicit SQLQueryModel(QString & t, QString & conn, QList<ColumnProperties> & cp, QVector<int> & ci, QObject* parent = 0): QSqlQueryModel(parent), table_(t), column_props(cp), column_indexes(ci), conn_name(conn) {;}
explicit SQLQueryModel(QString & t, QString & conn, QList<ColumnProperties> & cp, QVector<int> & ci, QObject * parent = 0)
: QSqlQueryModel(parent)
, table_(t)
, column_props(cp)
, column_indexes(ci)
, conn_name(conn) {
;
}
virtual QVariant data(const QModelIndex & item, int role = Qt::DisplayRole) const;
protected:
virtual Qt::ItemFlags flags(const QModelIndex & ) const {return (Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable);}
virtual bool setData(const QModelIndex & index, const QVariant& value, int role = Qt::EditRole);
int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];}
virtual Qt::ItemFlags flags(const QModelIndex &) const { return (Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable); }
virtual bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);
int mapColumn(int abs_ind) const {
if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0;
return column_indexes[abs_ind - 1];
}
QString & table_;
QList<ColumnProperties> & column_props;
QVector<int> & column_indexes;
@@ -108,20 +145,30 @@ signals:
};
class QAD_SQL_TABLE_EXPORT SQLUniEdit: public QWidget {
Q_OBJECT
public:
explicit SQLUniEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent = 0);
~SQLUniEdit() {for (int i = 0; i < w_.size(); ++i) deleteW(*w_[i]);}
~SQLUniEdit() {
for (int i = 0; i < w_.size(); ++i)
deleteW(*w_[i]);
}
void setProp(const ColumnProperties & p);
QString value(bool for_insert = false);
void clear() {setValue(QVariant());}
void clear() { setValue(QVariant()); }
private:
void deleteW(QWidget * w) {if (w != 0) delete w;}
void resizeW(QWidget * w) {if (w != 0) w->setGeometry(QRect(0, 0, width(), height()));}
void resizeEvent(QResizeEvent * ) {for (int i = 0; i < w_.size(); ++i) resizeW(*w_[i]);}
void deleteW(QWidget * w) {
if (w != 0) delete w;
}
void resizeW(QWidget * w) {
if (w != 0) w->setGeometry(QRect(0, 0, width(), height()));
}
void resizeEvent(QResizeEvent *) {
for (int i = 0; i < w_.size(); ++i)
resizeW(*w_[i]);
}
bool eventFilter(QObject * o, QEvent * e);
QLineEdit * wtext;
QSpinBox * wint;
@@ -130,36 +177,39 @@ private:
QTimeEdit * wtime;
QDateTimeEdit * wdatetime;
QComboBox * wrelation;
QList<QWidget ** > w_;
QList<QWidget **> w_;
ColumnProperties prop_;
QString connection_name;
private slots:
void value_text(QString value) {valueChanged(value);}
void value_int(int value) {valueChanged(value);}
void value_float(double value) {valueChanged(value);}
void value_date(QDate value) {valueChanged(value);}
void value_time(QTime value) {valueChanged(value);}
void value_datetime(QDateTime value) {valueChanged(value);}
void value_text(QString value) { valueChanged(value); }
void value_int(int value) { valueChanged(value); }
void value_float(double value) { valueChanged(value); }
void value_date(QDate value) { valueChanged(value); }
void value_time(QTime value) { valueChanged(value); }
void value_datetime(QDateTime value) { valueChanged(value); }
public slots:
void setValue(const QVariant & value);
void updateRelation();
signals:
void valueChanged(const QVariant & );
void valueChanged(const QVariant &);
};
class QAD_SQL_TABLE_EXPORT SQLNewEdit: public QWidget {
Q_OBJECT
friend class SQLTableWidget;
public:
explicit SQLNewEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent = 0);
~SQLNewEdit() {delete line; delete check;}
~SQLNewEdit() {
delete line;
delete check;
}
void setProp(const ColumnProperties & p);
bool isEnabled() const {return check->isChecked();}
QString value() const {return line->value(true);}
void clear() {line->clear();}
bool isEnabled() const { return check->isChecked(); }
QString value() const { return line->value(true); }
void clear() { line->clear(); }
private:
ColumnProperties prop_;
SQLUniEdit * line;
@@ -167,43 +217,54 @@ private:
};
class QAD_SQL_TABLE_EXPORT SQLFilterEdit: public QWidget {
Q_OBJECT
friend class SQLTableWidget;
public:
explicit SQLFilterEdit(const ColumnProperties & prop, const QString & conn_name, QWidget * parent = 0);
~SQLFilterEdit() {delete line; delete combo;}
void setProp(const ColumnProperties & p) {prop_ = p; line->setProp(p);}
~SQLFilterEdit() {
delete line;
delete combo;
}
void setProp(const ColumnProperties & p) {
prop_ = p;
line->setProp(p);
}
QString filter() const;
bool isEmpty() const {return line->value().isEmpty() || combo->currentIndex() == 0;}
bool isEmpty() const { return line->value().isEmpty() || combo->currentIndex() == 0; }
void clear();
private:
ColumnProperties prop_;
SQLUniEdit * line;
QComboBox * combo;
private slots:
void value_changed() {if (combo->currentIndex() == 0) combo->setCurrentIndex(prop_.is_text ? 2 : 1);}
void value_changed() {
if (combo->currentIndex() == 0) combo->setCurrentIndex(prop_.is_text ? 2 : 1);
}
public slots:
signals:
void filterChanged();
};
class QAD_SQL_TABLE_EXPORT SQLItemDelegate: public QStyledItemDelegate {
Q_OBJECT
public:
explicit SQLItemDelegate(QList<ColumnProperties> & cp, QVector<int> & ci, bool & ro, const QString & conn_name, QObject * parent = 0);
~SQLItemDelegate() {;}
~SQLItemDelegate() { ; }
private:
QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const;
QString displayText(const QVariant & value, const QLocale & locale) const;
void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const;
int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];}
void setConnectionName(const QString & conn_name) {connection_name = conn_name;}
int mapColumn(int abs_ind) const {
if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0;
return column_indexes[abs_ind - 1];
}
void setConnectionName(const QString & conn_name) { connection_name = conn_name; }
QList<ColumnProperties> & column_props;
QVector<int> & column_indexes;
bool & read_only;
@@ -215,12 +276,11 @@ signals:
namespace Ui {
class SQLTableWidget;
class SQLTableWidget;
}
class QAD_SQL_TABLE_EXPORT SQLTableWidget: public QWidget
{
class QAD_SQL_TABLE_EXPORT SQLTableWidget: public QWidget {
Q_OBJECT
Q_PROPERTY(QString tableName READ tableName WRITE setTableName)
Q_PROPERTY(QString connectionName READ connectionName WRITE setConnectionName)
@@ -230,105 +290,165 @@ class QAD_SQL_TABLE_EXPORT SQLTableWidget: public QWidget
Q_PROPERTY(bool debugEnabled READ isDebugEnabled WRITE setDebugEnabled)
friend class SQLItemDelegate;
friend class SQLUniEdit;
public:
SQLTableWidget(QWidget * parent = 0);
virtual ~SQLTableWidget();
bool isTableExists() const {return table_opened;}
const QString & tableName() const {return table_;}
bool isTableExists() const { return table_opened; }
const QString & tableName() const { return table_; }
QTableView * tableView();
bool readOnly() const {return read_only;}
bool readOnly() const { return read_only; }
void setDebugEnabled(bool on) {debug = on;}
bool isDebugEnabled() const {return debug;}
const ColumnProperties * columnProperty(int index) const {if (index < 0 || index >= column_props.count()) return 0; return &(column_props[index]);}
const ColumnProperties * columnProperty(const QString & name) const {return columnProperty(columnByName(name));}
const QList<ColumnProperties> & columnProperties() const {return column_props;}
QStringList columnNames() const {QStringList sl; foreach (const ColumnProperties & i, column_props) sl << i.name; return sl;}
int columnsCount() const {return column_props.size();}
bool isColumnVisible(int ind) {if (!columnExists(ind)) return false; return column_props[ind].visible;}
bool isColumnVisible(const QString & name) {if (!columnExists(name)) return false; return column_props[columnByName(name)].visible;}
bool isColumnHidden(int ind) {if (!columnExists(ind)) return true; return !column_props[ind].visible;}
bool isColumnHidden(const QString & name) {if (!columnExists(name)) return true; return !column_props[columnByName(name)].visible;}
void setDebugEnabled(bool on) { debug = on; }
bool isDebugEnabled() const { return debug; }
const ColumnProperties * columnProperty(int index) const {
if (index < 0 || index >= column_props.count()) return 0;
return &(column_props[index]);
}
const ColumnProperties * columnProperty(const QString & name) const { return columnProperty(columnByName(name)); }
const QList<ColumnProperties> & columnProperties() const { return column_props; }
QStringList columnNames() const {
QStringList sl;
foreach(const ColumnProperties & i, column_props)
sl << i.name;
return sl;
}
int columnsCount() const { return column_props.size(); }
bool isColumnVisible(int ind) {
if (!columnExists(ind)) return false;
return column_props[ind].visible;
}
bool isColumnVisible(const QString & name) {
if (!columnExists(name)) return false;
return column_props[columnByName(name)].visible;
}
bool isColumnHidden(int ind) {
if (!columnExists(ind)) return true;
return !column_props[ind].visible;
}
bool isColumnHidden(const QString & name) {
if (!columnExists(name)) return true;
return !column_props[columnByName(name)].visible;
}
void setColumnVisible(int ind, bool visible);
void setColumnVisible(const QString & name, bool visible) {col_vis[name] = visible; setColumnVisible(columnByName(name), visible);}
void setColumnHidden(int ind, bool hidden) {setColumnVisible(ind, !hidden);}
void setColumnHidden(const QString & name, bool hidden) {col_vis[name] = !hidden; setColumnVisible(columnByName(name), !hidden);}
void setColumnVisible(const QString & name, bool visible) {
col_vis[name] = visible;
setColumnVisible(columnByName(name), visible);
}
void setColumnHidden(int ind, bool hidden) { setColumnVisible(ind, !hidden); }
void setColumnHidden(const QString & name, bool hidden) {
col_vis[name] = !hidden;
setColumnVisible(columnByName(name), !hidden);
}
bool lineNewVisible() const;
bool lineFilterVisible() const;
bool addRelation(const QString & this_column, const QString & other_table, const QString & other_key, const QString & other_column);
void addTranslation(const QString & file);
void addFixedColumnTranslation(const QString & col_name, const QString & col_tr, const QString & col_tt = QString());
void fetchMore() {if (model) model->fetchMore();}
void fetchAll() {if (model) while (model->canFetchMore()) model->fetchMore();}
void fetchMore() {
if (model) model->fetchMore();
}
void fetchAll() {
if (model)
while (model->canFetchMore())
model->fetchMore();
}
void selectId(int id);
void setAdditionalActions(QList<QAction * > a);
QSqlRecord headerRecord() const {if (model) return model->record(); return QSqlRecord();}
QSqlRecord currentRecord() const;
void setCustomQuery(const QString & q);
void setCustomColumnNames(const QStringList & cn) {custom_col_names = cn; updateTable();}
static bool isTableExists(const QString & table, const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) {return QSqlDatabase::database(conn_name).tables().contains(table, Qt::CaseInsensitive);}
void setAdditionalActions(QList<QAction *> a);
static bool executeScript(const QString & text, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false);
static bool executeScriptFile(const QString & file, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false);
static bool isConnectedToDatabase(const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) {return QSqlDatabase::database(conn_name, false).isOpen();}
QSqlRecord headerRecord() const {
if (model) return model->record();
return QSqlRecord();
}
QSqlRecord currentRecord() const;
void setCustomQuery(const QString & q);
void setCustomColumnNames(const QStringList & cn) {
custom_col_names = cn;
updateTable();
}
static bool isTableExists(const QString & table, const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) {
return QSqlDatabase::database(conn_name).tables().contains(table, Qt::CaseInsensitive);
}
static bool
executeScript(const QString & text, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false);
static bool
executeScriptFile(const QString & file, QSqlDatabase db = QSqlDatabase::database(), bool skip_errors = false, bool sqlite = false);
static bool isConnectedToDatabase(const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection)) {
return QSqlDatabase::database(conn_name, false).isOpen();
}
static bool connectToDatabase(const QString & config, const QString & conn_name = QLatin1String(QSqlDatabase::defaultConnection));
QString connectionName() const {return connection_name;}
QString connectionName() const { return connection_name; }
private:
static QString preprocessScript(QString text);
bool eventFilter(QObject * o, QEvent * e);
void timerEvent(QTimerEvent * );
void timerEvent(QTimerEvent *);
void changeEvent(QEvent * e);
void stopTimer() {if (timer != 0) killTimer(timer); timer = 0;}
void stopTimer() {
if (timer != 0) killTimer(timer);
timer = 0;
}
bool checkTable();
QStringList getTableColumns(const QString & t);
QString getColumnType(const QString & t, const QString & c);
static QList<QPair<QString, QString> > getColumnValues(const QString & t, const QString & k, const QString & c, const QString & conn_name);
static QList<QPair<QString, QString>>
getColumnValues(const QString & t, const QString & k, const QString & c, const QString & conn_name);
void setTableVisible(bool on);
int mapColumn(int abs_ind) const {if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0; return column_indexes[abs_ind - 1];}
int columnByName(const QString & name) const {for (int i = 0; i < column_props.size(); ++i) if (column_props[i].name == name) return i; return -1;}
bool columnExists(int index) const {return (index >= 0 && index < column_props.size());}
bool columnExists(const QString & name) const {for (int i = 0; i < column_props.size(); ++i) if (column_props[i].name == name) return true; return false;}
int mapColumn(int abs_ind) const {
if (abs_ind <= 0 || abs_ind >= column_indexes.size() + 1) return 0;
return column_indexes[abs_ind - 1];
}
int columnByName(const QString & name) const {
for (int i = 0; i < column_props.size(); ++i)
if (column_props[i].name == name) return i;
return -1;
}
bool columnExists(int index) const { return (index >= 0 && index < column_props.size()); }
bool columnExists(const QString & name) const {
for (int i = 0; i < column_props.size(); ++i)
if (column_props[i].name == name) return true;
return false;
}
QPair<QString, QString> trColumn(const QString & n);
QString tableNames();
QString columnNames();
QString columnFilters();
QString columnRelations();
Ui::SQLTableWidget * ui;
QString table_, cquery, custom_query;
QStringList custom_col_names;
SQLQueryModel * model;
//QAction act_add, act_del;
// QAction act_add, act_del;
QList<ColumnProperties> column_props;
QList<SQLNewEdit * > column_news;
QList<SQLFilterEdit * > column_filters;
QList<SQLNewEdit *> column_news;
QList<SQLFilterEdit *> column_filters;
QVector<int> column_indexes;
QStringList wait_rels;
QMenu popup_menu, popup_col, popup_filter;
QElapsedTimer tm;
QActionGroup filters_group;
QAction * action_del;
QList<QAction*> add_actions;
QMap<QString, QPair<QString, QString> > translates, fixed_translates;
QList<QAction *> add_actions;
QMap<QString, QPair<QString, QString>> translates, fixed_translates;
QMap<QString, bool> col_vis;
int timer;
bool filters_active, table_opened, read_only, first_update, debug;
static QString _dir;
QPoint pp;
QString connection_name;
public slots:
void setTableName(const QString & t);
@@ -336,7 +456,7 @@ public slots:
void setLineFilterVisible(bool on);
void setReadOnly(bool yes);
void updateTable(bool save_selection = false);
void setConnectionName(const QString &conn_name);
void setConnectionName(const QString & conn_name);
private slots:
void on_buttonAdd_clicked();
@@ -347,13 +467,12 @@ private slots:
void scrolled(int value);
void del_triggered();
void column_triggered(bool on);
signals:
void rowClicked(int row);
void recordClicked(QSqlRecord rec);
void selectionChanged();
void tableChanged();
};