I've got a question regarding my vector iteration method within a Qt/MySQL++ project I'm working on at the moment.
I've been using for loops to iterate through them so far, and being quite a beginner at C++, didn't realise that the generally accepted method is to use vector::iterator. I've been trying to see a way I can convert them to this model, but I'm a bit stuck. My code reads as follows:
(connector is an instance of my custom db connection class)
mysqlpp::StoreQueryResult res = connector->getResults(searchTerm);
int stock = res.field_num("stock");
if(res.num_rows() > 0)
{
tblStock->setRowCount(res.num_rows());
for(size_t i = 0; i < res.num_rows(); i++)
{
tblStock->setItem(i, 0,
new QTableWidgetItem(QString(res[i][stock].c_str())));
}
}
My problem is that I can't see a way to just use a vector::iterator instead of the incremental size_t, given that I am using i
to define where to set the QTableWidgetItem. It definitely seems absurd to use both, though.
Any ideas?
Many thanks in advance for anybody and everybody!
X-T
UPDATE: Changed my program to use QSql objects, and a tableView, instead of a tableWidget, and it all works wonderfully! Thanks to anybody who took time to read the question!
Is it any serious reason you don't use QSql? I think QSqlQueryModel + QTableView can solve your problem without any vectors and iterators. A small example, right from Qt help:
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT name, salary FROM employee");
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new QTableView;
view->setModel(model); // binding model to view
view->show();
You probably have to read something about Qt model/view classes and about QSql to fully understand this example, but this is worth reading. I think you will have no problem reading Qt Reference, it is very detailed.