PDA

View Full Version : How to detect data changes in Widgets and transfer them to DB?



zubr
9th March 2007, 20:02
How to detect data changes in Widgets and to transfer them to DB? QDataWidgetMapper and QSqlTableModel are used.
Now changes are detect manually through connect textChanged(QString &) - for QLineEdit, editTextChanged(QString &) - for QComboBox, etc. It is possible to automate or make uniform detecting data changes?
Now changes are transfer through QSqlTableModel::setRecord(int,const QSqlRecord &). It is possible to make it through the delegate?

vfernandez
9th March 2007, 21:07
You may subclass QLineEdit, QComboBox, etc and implement a method where you store the data in the database and connect the textChanged(), activated(), etc signals to your method in the subclass. That way you'll only need to implement storing the data only once for each type of widget instead of for each widget instance. For instance:

mylineedit.h

class MyLineEdit : public QLineEdit {

Q_OBJECT

public:
MyLineEdit(QWidget *parent = 0);

void setQuery(const QString& query);

public slots:
void startQuery(const QString& text);

private:
QString m_query;
};

mylineedit.cpp

MyLineEdit::MyLineEdit(QWidget *parent)
: QLineEdit(parent) {
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(startQuery(const QString&));
}

void MyLineEdit::setQuery(const QString& query)
{
m_query = query;
}

void MyLineEdit::startQuery(const QString& text)
{
QString q = m_query.arg(text);
// execute the query stored in "q"
}

to use:

MyLineEdit *lineEdit = new MyLineEdit(this);
lineEdit->setQuery("INSERT INTO table VALUES('%1');");

Anyway, I wouldn't recommend you executing a SQL query directly from the GUI thread since it will block the GUI unless you're using it in a local network. Instead, better create a thread that handles the queries.