bool MusicUserModel::addUser(const QString &uid, const QString &pwd,
                             const QString &mail)
{
    setTable("MusicUser");
    select();

    insertRow(0);
    setData(index(0, fieldIndex("USERID")), uid);
    setData(index(0, fieldIndex("PASSWD")), userPasswordEncryption(pwd));
    setData(index(0, fieldIndex("EMAIL")), mail);
    setData(index(0, fieldIndex("USERNAME")), uid);
    setData(index(0, fieldIndex("LOGINTIME")), 0);
    database().transaction();
    if(submitAll())
    {
        database().commit();
        M_LOGGER_INFO("submit successfully");
        return true;
    }
    else
    {
        M_LOGGER_INFO("submit failed");
        database().rollback();
        return false;
    }
}
Esempio n. 2
0
/*!
    This reimplemented slot is called by the item delegates when the
    user stopped editing the current row.

    Submits the currently edited row if the model's strategy is set
    to OnRowChange or OnFieldChange. Does nothing for the OnManualSubmit
    strategy.

    Use submitAll() to submit all pending changes for the
    OnManualSubmit strategy.

    Returns true on success; otherwise returns false. Use lastError()
    to query detailed error information.

    On success the model will be repopulated. Any views 
    presenting it will lose their selections.

    \sa revert(), revertRow(), submitAll(), revertAll(), lastError()
*/
bool QSqlTableModel::submit()
{
    Q_D(QSqlTableModel);
    if (d->strategy == OnRowChange || d->strategy == OnFieldChange)
        return submitAll();
    return true;
}
Esempio n. 3
0
void BookmarkModel::remove(const QString& url)
{
    if (!contains(url))
        return;

    QSqlQuery sqlQuery(database());
    sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?"));
    sqlQuery.addBindValue(url);
    sqlQuery.exec();
    sqlQuery.first();
    int indexToDelete = -1;
    for (int row = 0; row < rowCount(); ++row) {
        if (createIndex(row, 0).data(Qt::DisplayRole).toInt() == sqlQuery.value(0).toInt()) {
            indexToDelete = row;
            break;
        }
    }

    if (indexToDelete >= 0) {
        beginRemoveRows(createIndex(indexToDelete, 0), indexToDelete, indexToDelete);
        removeRow(indexToDelete);
        submitAll();
        endRemoveRows();
    }
}
Esempio n. 4
0
/*!
    \fn MGasto::agregarGasto( QString descripcion, double costo, QDate Fecha, int categoria )
 */
bool MGasto::agregarGasto( QString descripcion, double costo, QDate Fecha, int categoria )
{
 QSqlTableModel::EditStrategy modo = this->editStrategy();
 this->setEditStrategy( QSqlTableModel::OnManualSubmit );
 QSqlRecord registro = this->record();
 registro.setValue( "descripcion", descripcion );
 registro.setValue( "costo", costo );
 registro.setValue( "fecha", Fecha );
 registro.setValue( "id_categoria", categoria );
 registro.remove( 0 );
 if( this->insertRecord( -1, registro ) == false )
 {
  qDebug( "Error al insertar registro de gasto" );
  qDebug() << "Detalles: tipo: " << lastError().type() << ", errno:" << lastError().number() << ", descripcion: " << lastError().text();
  this->setEditStrategy( modo );
  return false;
 }
 else
 {
     if( submitAll() )
     {
         qDebug( "Gasto agregado correctamente" );
         this->setEditStrategy( modo );
         return true;
     }
     else
     {
         qDebug( "Error al insertar registro de gasto" );
         qDebug() << "Detalles: tipo: " << lastError().type() << ", errno:" << lastError().number() << ", descripcion: " << lastError().text();
         this->setEditStrategy( modo );
         return false;
     }

 }
}
Esempio n. 5
0
void FilmModel::deleteFilms(QList<int> rows)
{
    for (int i = 0; i < rows.size(); i++)
    {
        removeRow(rows.at(i));
    }
     submitAll();
}
void MobileTableModel::refreshMobileTable(const QVector<int> mobileMsg)
{
    int fixId,mode,dstAddr,period,selfAddr;
    QString dst,self;
    dst.fill('0',4);
    self.fill('0',4);
    fixId = mobileMsg.at(M_FIXID);
    mode = mobileMsg.at(M_LOC_MODE);
    dstAddr = mobileMsg.at(M_DST_ADDR_LO);
    dstAddr |= (mobileMsg.at(M_DST_ADDR_HI) << 8);
    dst.append(QString::number(dstAddr,16).toUpper());//转为十六进制
    period = mobileMsg.at(M_LOC_PERIOD);
    selfAddr = mobileMsg.at(M_SELF_ADDR_LO);
    selfAddr |= (mobileMsg.at(M_SELF_ADDR_HI) << 8);
    self.append(QString::number(selfAddr,16).toUpper());
    //添加或者更新参考节点配置信息数据表
    setFilter("fixId = " + QString::number(fixId));
    select();
    if(rowCount() == 1)//已经存在,更新数据
    {
        QSqlRecord record = this->record(0);
        record.setValue("fixId",fixId);
        record.setValue("mode", mode);
        record.setValue("dstAddr", dst.right(4));
        record.setValue("period", period);
        record.setValue("selfAddr", self.right(4));
        setRecord(0, record);
        submitAll();
        setFilter("");//清除过滤条件,否则只显示更新的一条
    }
    else if(rowCount() == 0)//不存在,添加新移动节点配置信息
    {
        int row = 0;
        insertRows(row, 1);
        setData(index(row, 1), fixId);
        setData(index(row, 2), mode);
        setData(index(row, 3), dst.right(4));
        setData(index(row, 4), period);
        setData(index(row, 5), self.right(4));
        submitAll();
        setFilter("");//清楚过滤条件,否则只显示更新的一条
        submitAll();
    }
}
Esempio n. 7
0
TableEditor::TableEditor(QWidget *parent): Editor(parent)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    setLayout(layout);

    // toolbar
    _toolbar = new QWidget(this);
    layout->addWidget(_toolbar);
    _ui_toolbar = new Ui::TableEditorToolbar;
    _ui_toolbar->setupUi(_toolbar);
    _ui_toolbar->firstPageButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/allLeft")));
    _ui_toolbar->previousPageButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/left")));
    _ui_toolbar->nextPageButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/right")));
    _ui_toolbar->lastPageButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/allRight")));

    _ui_toolbar->refreshButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/refresh")));

    _ui_toolbar->addRowButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/general/add")));
    _ui_toolbar->deleteRowButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/general/remove")));

    _ui_toolbar->commitButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/checked")));
    _ui_toolbar->rollbackButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/rollback")));

    _ui_toolbar->dumpDataButton->setIcon(QIcon(IconLoader::getIconIdentifier(":/drawable/actions/export")));

    _tableView = new QTableView(this);
    _tableModel = new QSqlTableModel(_tableView /* TODO database connection */);
    _tableView->setModel(_tableModel);
    layout->addWidget(_tableView);

    // connections
    connect(_ui_toolbar->commitButton, SIGNAL(clicked()), _tableModel, SLOT(submitAll()));
    connect(_ui_toolbar->rollbackButton, SIGNAL(clicked()), _tableModel, SLOT(revertAll()));
    connect(_ui_toolbar->addRowButton, SIGNAL(clicked()), this, SLOT(addRow()));
    connect(_ui_toolbar->deleteRowButton, SIGNAL(clicked()), this, SLOT(deleteRows()));
    connect(_ui_toolbar->refreshButton, SIGNAL(clicked()), _tableModel, SLOT(select()));



    connect(_ui_toolbar->toolButtonExportImage, SIGNAL(clicked()),_imageView, SLOT(exportImage()));
    connect(_ui_toolbar->toolButtonZoomIn, SIGNAL(clicked()),_imageView,SLOT(zoomIn()));
    connect(_ui_toolbar->toolButtonZoomOut, SIGNAL(clicked()),_imageView, SLOT(zoomOut()));
    connect(_ui_toolbar->toolButtonFitToScreen, SIGNAL(clicked()),_imageView, SLOT(fitToScreen()));
    connect(_ui_toolbar->toolButtonOriginalSize, SIGNAL(clicked()),_imageView, SLOT(resetToOriginalSize()));
    connect(_ui_toolbar->toolButtonBackground, SIGNAL(toggled()),_imageView, SLOT(setViewBackground()));
    connect(_ui_toolbar->toolButtonOutline, SIGNAL(toggled()),_imageView, SLOT(setViewOutline()));
    connect(_ui_toolbar->toolButtonPlayPause, SIGNAL(clicked()),this, SLOT(playToggled()));
    connect(_file, SIGNAL(imageSizeChanged()),this, SLOT(imageSizeUpdated()));
    connect(_file, SIGNAL(openFinished()),_imageView, SLOT(createScene()));
    connect(_file, SIGNAL(openFinished()),this, SLOT(updateToolButtons()));
    connect(_file, SIGNAL(aboutToReload()),_imageView, SLOT(reset()));
    connect(_file, SIGNAL(reloadFinished()),_imageView, SLOT(createScene()));
    connect(_file, SIGNAL(isPausedChanged()),this, SLOT(updatePauseAction()));
    connect(_imageView, SIGNAL(scaleFactorChanged()),this, SLOT(scaleFactorUpdate()));
}
Esempio n. 8
0
void BookmarkModel::update(int index, const QString& name, const QString& url)
{
    QModelIndex nameIndex = createIndex(index, 1);
    QModelIndex urlIndex = createIndex(index, 2);
    QModelIndex dateAddedIndex = createIndex(index, 3);
    setData(nameIndex, name);
    setData(urlIndex, url);
    setData(dateAddedIndex, QDateTime::currentDateTime().toTime_t());
    emit dataChanged(nameIndex, dateAddedIndex);
    submitAll();
}
Esempio n. 9
0
/**
 * Bases model view programming qt
 * ================================
 *
 * @brief MainWindow::MainWindow
 * @param parent
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /*
     * Initialisation du model
     */
    setUpModel();


    /*
     * On utilise deux vue pour représenter le model
     *
     *
     * 1) Le model est connecté à la base de donnée
     *    Si l'EditStrategy == onManualSubmit, le model ne pas tout
     *    seul à jout la base de donnée, il faut dans ce cas appeler submitAll()
     *
     *
     * 2) Les vue ne sont pas connectées à la base de donnée mais au Model.
     *    Donc même sans submitAll(), toutes les vues représantant le model sont mise à jour
     *
     *
     * Pour mettre à jour la base de donnée simplement, deux solutions possible:
     * a) créer un slot updateModel() qui fait juste un submitAll ez le connecter un bouton.
     *    Dans ce cas l'utilisateur met à jour la database manuellement avec un bouton save.
     *
     *
     * b) ou connecter le signal dataChanged() du model au slotSumbitAll.
     *    Dans ce cas au moindre changement du model depuis une vue ou depuis le code, la database est mise à jour
     */

    QHBoxLayout* layout = new QHBoxLayout();
    viewTable = new QTableView;
    viewList = new QListView;
    viewTable->setModel(model);  // les deux vues représentent le même model
    viewList->setModel(model);
    viewList->setModelColumn(1); // la liste affiche la deuxième colonne

    layout->addWidget(viewTable);
    layout->addWidget(viewList);

    layout->setContentsMargins(0,0,0,0);
    ui->centralWidget->setLayout(layout);

    // Ici on choisi la solution b) pour mettre à jour la database
    connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), model, SLOT(submitAll()));

}
void ReferTableModel::refreshReferTable(const QVector<int> referenceMsg)
{
    QString hexNetId;
    int floor,number;
    hexNetId.fill('0',4);//用于补充不够4位netID的前面的0

    int netId,tmpPeriod;
    floor = referenceMsg.at(R_ROOM_FLOOR);
    number = referenceMsg.at(R_ROOM_NUMBER);
    netId = referenceMsg.at(R_NETID_LO);
    netId |= (referenceMsg.at(R_NETID_HI) << 8);
    hexNetId.append(QString::number(netId,16).toUpper());
    tmpPeriod = referenceMsg.at(R_TEMP_PERIOD);
    //添加或者更新参考节点配置信息数据表
    setFilter(QString("floor=%1 AND number=%2").arg(floor).arg(number));
    select();
    if(rowCount() == 1)//已经存在,更新netId
    {
        QSqlRecord record = this->record(0);
        record.setValue("netId",hexNetId.right(4));
        record.setValue("tempPeriod", tmpPeriod);
        setRecord(0,record);
        submitAll();
        setFilter("");//清楚过滤条件,否则只显示更新的一条
    }
    else if(rowCount() == 0)//不存在,添加netId
    {
        int row = 0;
        insertRows(row, 1);
        setData(index(row, 1),hexNetId.right(4));
        setData(index(row, 2), floor);
        setData(index(row, 3),number);
        setData(index(row, 4), tmpPeriod);
        submitAll();
        setFilter("");//清楚过滤条件,否则只显示更新的一条
        submitAll();
    }
}
Esempio n. 11
0
void FilmModel::updateFilm(int row, Film f)
{
    QSqlRecord r = record(row);
    r.setValue("name", f.name);
    r.setValue("country", f.country);
    r.setValue("year", f.year);
    r.setValue("actors", f.actors);
    r.setValue("director", f.director);
    r.setValue("type", f.type == serial ? 1 : 0);
    r.setValue("genre", f.genre);
    r.setValue("score", f.score);
    r.setValue("poster", "");
    setRecord(row,r);
    submitAll();
}
Esempio n. 12
0
bool FilmModel::addFilm(Film &f)
{
    QSqlRecord r = record();
    r.setValue("name", f.name);
    r.setValue("year", f.year);
    r.setValue("country", f.country);
    r.setValue("director", f.director);
    r.setValue("actors", f.actors);
    r.setValue("type", f.type);
    r.setValue("genre", f.genre);
    r.setValue("score", f.score);
    r.setValue("poster", "");
    insertRecord(-1, r);
    bool resSubmit = submitAll();
    return resSubmit;
}
Esempio n. 13
0
void BookmarkModel::insert(const QString& name, const QString& url)
{
    if (url.isEmpty() || contains(url))
        return;
    QModelIndex index = QModelIndex();
    beginInsertRows(index, rowCount(index), rowCount(index));
    QSqlQuery sqlQuery(database());
    static QString insertStatement = QLatin1String("INSERT INTO bookmarks (name, url, dateAdded) VALUES (?, ?, ?)");
    sqlQuery.prepare(insertStatement);
    sqlQuery.addBindValue(name);
    sqlQuery.addBindValue(url);
    sqlQuery.addBindValue(QDateTime::currentDateTime().toTime_t());
    sqlQuery.exec();
    select();
    endInsertRows();
    submitAll();
}
Esempio n. 14
0
void ContextModel::addNewContext(QString newContext)
{

    if (newContext.isEmpty())
    {
        return;
    }
    QSqlQuery query;
    query.prepare("select count(id) from context where shortdescr like :context");
    query.bindValue(":context", newContext);
    query.exec();
    if (query.next())
    {
        if (query.record().value("count(id)").toInt() > 0)
            return;
    }

    qDebug() << "save new context " << newContext << " in database.";

    QSqlRecord record;
    QSqlField shortDescr = QSqlField("shortdescr", QVariant::String);
    shortDescr.setValue(newContext);
    record.append(shortDescr);
    QSqlField id = QSqlField("id", QVariant::Int);
    shortDescr.setValue(20);
    record.append(id);

    if(!insertRecord( -1, record))
    {
        qDebug("could not create new context.");

    }
    if (!submitAll())
    {
        qDebug("could not create new context.");
    }

    select();
}
Esempio n. 15
0
ProvidersDialog::ProvidersDialog(QWidget *parent, LkSettingsManager *settings, QSqlDatabase *db) :
    QDialog(parent),
    ui(new Ui::ProvidersDialog)
{
    ui->setupUi(this);

    m_settings = settings;
    connect(ui->checkBox, SIGNAL(toggled(bool)), m_settings, SLOT(setShowAllProvs(bool)));

    m_model = new LkSqlTableModel(this, *db);
    m_model->setTable("Providers");
    m_model->setFilter("is_deleted = 0");

    QSqlError er = m_model->lastError();

    if(er.type() != QSqlError::NoError) {
        QMessageBox::critical(this, tr("Ошибка открытия таблицы"), tr("Ошибка %1\n%2").arg( QString::number(er.type()), er.text()), QMessageBox::Close);
    }

    connect(this, SIGNAL(accepted()), m_model, SLOT(submitAll()));

    initModel();
}