Qt C++ Get data from a selected row of a table view - c++

I have a table view populated with data of Vehicle objects stored in a QList<Vehicle> cars; On this cars list i have to make some actions: search, add, edit, delete; After every action of search, i store the founded objects in another list to populate the table view only with this objects, keeping the original list intact. The original list gets modified only on add, edit or delete. Here comes the problem: i search for an object that i want to edit, it is shown in the table view, i select it and press the edit button; i am using QModelIndexList to get the index of the row. The index of the row will give me the position from the "founded" list, and i need to modify the object in the original list. Below is my implementation.
Is there any other way to this thing without the temporary list? How can i modify the original object using Iterator, instead that for loop?
void MainWindow::on_actionEdit_triggered()
{
QMessageBox msgBox;
QModelIndexList id = ui->tableView->selectionModel()->selectedIndexes();
if(id.isEmpty()){
msgBox.setWindowTitle("Message");
msgBox.setText("Please select a row");
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
} else{
int row = id.at(0).row();
QUuid carId = temp.at(row).getVehicleID(); // temp -> the "the founded" list
for(int i = 0; i < cars.size(); i++){
Vehicle& current = cars[i];
Vehicle& currentTemp = temp[row];
if(carId == current.getVehicleID() && carId == currentTemp.getVehicleID()){
addDialog = new AddEditDialog(this);
addDialog->loadVehicleToEdit(current);
addDialog->exec();
if(addDialog->getIsEdited()){
current = addDialog->getVehicleToAdd();
currentTemp = addDialog->getVehicleToAdd();
currentTemp.setVehicleId(carId);
current.setVehicleId(carId);
}
}
}
}
//create header
createHeader(model);
//set data to the table view
populate(temp);
}

May be you use proxy model and you need to call mapToSource?

Related

Always show a QComboBox in a cell of a QTableView

I have a QTableView with an associated model. I want to have a QComboBox in each cell of the third column.
I used a QItemDelegate as shown in this page : https://wiki.qt.io/Combo_Boxes_in_Item_Views.
It works but the combo box is only shown after double clicking in the cell, the user has to click again to show the list of possible values. This is a bit inconvenient.
Is there a way to make the combo boxes always visible ?
I'm trying with openPersistentEditor method, but it does not work right now ...
there is a bit of code close to my code (ComboBoxItemDelegate is the same than the exemple linked before):
MonWidget::MonWidget() : _ui(new Ui::MonWidget())
{
// ...
// Links Model
_linksModel = new QStandardItemModel(this);
// Links Headers
QStringList linksTableViewHeader << "Name" << "Path" << "Version";
_linksModel->setHorizontalHeaderLabels(linksTableViewHeader) ;
// Create itemDelegate for linksView
_itemDelegate = new ComboBoxItemDelegate(_ui->_linksView);
// Set the links model on the links table view
_ui->_linksView->setModel(_linksModel);
_ui->_linksView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
_ui->_linksView->horizontalHeader()->setStretchLastSection(true);
_ui->_linksView->horizontalHeader()->setMinimumSectionSize(100);
_ui->_linksView->setSelectionBehavior(QAbstractItemView::SelectRows);
_ui->_linksView->setItemDelegate(_itemDelegate);
}
// AddLinksInListView : method called when I add some rows ...
void MonWidget::AddLinksInListView(QList<DataItem*> listLinks)
{
int j=0;
int initialLinksNumber = _linksModel->rowCount();
// For each link, add a row with the link information
for (int row=initialLinksNumber; row<(initialLinksNumber + listLinks.size()) ; row++)
{
for (int column = 0; column < _linksModel->columnCount(); column++) {
//item used to display information for each column in the table view of links contained in the collection
QStandardItem *item=0;
switch(column)
{
case MonWidget::NAME:
{
item = new QStandardItem(listLinks.at(j)->data(MonWidget::NAME).toString());
_linksModel->setItem(row, column, item);
break;
}
case MonWidget::PATH:
{
item = new QStandardItem(listLinks.at(j)->data(MonWidget::PATH).toString());
_linksModel->setItem(row, column, item);
break;
}
case MonWidget::VERSION:
{
item = new QStandardItem(listLinks.at(j)->data(MonWidget::PATH).toString());
_linksModel->setItem(row, column, item);
_ui->_linksView->openPersistentEditor(_linksModel->index(row, column));
break;
}
}
}
j++;
}
}
Yes, there is a way, using openPersistentEditor. Assuming your model is named myModel:
YourDelegate* comboDelegate = new YourDelegate(this);
setItemDelegateForColumn(2, comboDelegate); // delegate set for the third column
...
// when adding a new line, use this.
// The combo box will be always visible
openPersistentEditor(myModel->index(iRow, 1));

Adjusting QSqlTableModel for a QTreeView

I'm trying to put a MySQL table into a treeView.
Each entry has three values in the database - id, text, parentId.
This treeView needs to be editable so I really like the QSqlTableModel approach, as the functionality to save back to database is already built in.
Now, the treeView is showing all entries in the same line, of course, and I need a hierarchy. What would be the best way to build this hierarchy, while maintaining the editing and saving capabilities?
(I'm using MySQL.)
mainwindow.h
private: QSqlTableModel* goalModel;
mainwindow.cpp
(this makes a flat table hierarchy. the table is filtered based on which entry is clicked in another table)
void MainWindow::on_tableViewGoals_clicked(const QModelIndex &index)
{
goalModel = new QSqlTableModel(this);
goalModel->setTable("goals");
//Gets the id from the clicked entry to use as filter
QString idGoals = index.sibling(row,0).data().toString();
goalModel->setFilter( "id_goals=" + idGoals );
goalModel->setEditStrategy(QSqlTableModel::OnRowChange);
goalModel->select();
ui->treeView->setModel(goalModel);
...
I tried this. It's wrong, but I don't really know why. (the third column contains the parentId value, if the entry has it)
for (int row = 0; row < goalModel->rowCount(); ++row)
{
//if the entry has a value over 0 in the parentId column
if (goalModel->index(row,2).data().toInt() > 0)
{
//get number in column 2
int parentId;
parentId = goalModel->index(row,2).data().toInt();
QModelIndex newChild = goalModel->index(row,0);
//find QModelIndex row with matching number in column 0
for (int row = 0; row < goalModel->rowCount(); ++row)
{
if (goalModel->index(row,0).data().toInt() == parentId )
{
//make this entry that entry's child
QModelIndex newParent = goalModel->index(row,0);
newChild = goalModel->index(0,0,newParent);
}
}
}
}
All indexes are already made, so no need to make new ones, just assign a parent to all those who have one. How best to do that?

QT - Can I dynamically point to GUI's labels using a variable passed into a method?

I'm creating an inventory and want to reference my inventory Forms QLabels with the name of the item passed into my method.
The QLabels and the names of the items are the same so I wanted to reduce if statements by referencing a QLabel depending on the name of the item passed in.
void Zork::on_btnTake_clicked()
{
Item *item = new Item(ui->takeItem->currentText().toStdString());
Colin->addItemToInventory(item);
inventory_screen->addItem(item->getDescription()); //Enables the Item in the Inventory
currentRoom->deleteItem(item);
ui->takeItem->removeItem(ui->takeItem->currentIndex()); //Only remove the item in the foreground of combobox at the time take button was clicked
}
Calls this Method addItemToInventory(item):
void Inventory_Ui:: addItem(string itemName){
myUi->itemName->setText(QString::fromStdString(itemName));
}
I am unable to do so as itemName is not a member of Ui, although itemName does contain members of Ui.
Example:
In my Inventory_Ui Form I have 6 labels, one named broken_bottle. I want to pass broken_bottle into the method's parameter itemName and them use that as a reference so at run-time it would look like myUi->broken_bottle->setText...
I think I follow what you are asking to do. I would access it with findChild or findChildren.
http://doc.qt.io/qt-5/qobject.html#findChild
http://doc.qt.io/qt-5/qobject.html#findChildren
QList <QLabel *> labels = ui->myForm()->findChildren<QLabel*>();
QLabel* targetLabel = 0;
foreach(QLabel * label, labels)
{
if(label->text() == ui->takeItem->currentText())
{
targetLabel = label;
break;
}
}
if(targetLabel != 0)
{
// ... do something with targetLabel
}
or...
QList <QLabel *> labels = ui->myForm()->findChildren<QLabel*>();
foreach(QLabel * label, labels)
label->setObjectName(label->text());
// later
QLabel * targetLabel = ui->myForm()->findChild<QLabel*>("text of label");
if(targetLabel)
// use it
Or if you are connecting all these labels to the same slot, you can figure some of it out using the sender static method.
http://doc.qt.io/qt-5/qobject.html#sender
void MainWindow::on_takeItem_currentTextChanged()
{
QLabel* targetLabel = qobject_cast<QLabel*>QObject::sender();
if(targetLabel)
// do something with it
}
Hope that helps.

Sitecore workbox change sort order

By default Sitecore workbox displays the Item name, and sort the item list by Item name.
In one of my previous posts regarding this I managed to change the item name to a custom field.
Now I need to sort workbox by this field. How can I do this?
Assuming that you already have your own implementation of the WorkboxForm as described in the post you linked in your question, you need to change the code of the DisplayState method.
The DataUri[] items inflow parameter of this method gives you the list of all items which are in given state of the workflows. You need to retrieve all the Sitecore items from this parameter and sort them:
DataUri[] items = new DataUri[0];
List<Item> sitecoreItems = items
.Select(uri => Context.ContentDatabase.Items[uri])
.OrderBy(item => item["YourCustomField"])
.ToList();
And use the new list for selecting the current page items. This solution is not optimized for the performance - you need to get every item in given state from database so you can access the custom field.
After studying Sitecore workbox modifications, I came across with following solution.
Step 1 - Modify the GetItems method as follows,
private DataUri[] GetItems(WorkflowState state, IWorkflow workflow)
{
if (workflow != null)
{
var items = workflow.GetItems(state.StateID);
Array.Sort(items, new Comparison<DataUri>(CompareDataUri));
return items;
}
return new DataUri[] { };
}
Here comes the "CompareDataUri" method,
private int CompareDataUri(DataUri x, DataUri y)
{
//Custom method written to compare two values - Dhanuka
Item itemX = Sitecore.Context.ContentDatabase.GetItem(x);
Item itemY = Sitecore.Context.ContentDatabase.GetItem(y);
string m_sortField = "__Updated";
bool m_descSort = false;
var res = 0;
res = string.Compare(itemX[m_sortField], itemY[m_sortField]);
if (m_descSort)
{
if (res > 0)
return -1;
if (res < 0)
return 1;
}
return res;
}
This approach is optimized for performance.

How to remove all rows and child rows from QTreeview

I don't know why I have trouble removing all rows and sub rows from qtreeview
I'm using QStandardItemModel as the model. Now here is my code that doesn't work.
What could be the problem?
QModelIndex FirstQModelIndex;
QModelIndex parentQModelIndex;
int iMdlChidCound = m_model->hasChildren();
if(iMdlChidCound > 0)
{
// only if there at list 1 row in the view
FirstQModelIndex = m_model->item(0,0)->index();
QStandardItem* feedItem = m_model->itemFromIndex(FirstQModelIndex);
// get the parent of the first row its the header row
QStandardItem* parentItem = feedItem->parent();
// here im getting exception
int parent_rows= parentItem->hasChildren();
parentQModelIndex = m_model->indexFromItem(parentItem);
// now i like to delete all the rows under the header , and its dosnt work
if(parent_rows>0)
{
bool b = feedItem->model()->removeRows(0,y,parentQModelIndex);
}
}
It seems like a lot of what you're doing is superfluous. If your only goal is to remove all the rows from the model, you could probably just use QStandardItemModel::clear
In your code you're jumping between the model and the items in a way you don't have to.
if(m_model->hasChildren()) {
m_model->removeRows(0, m_model->rowCount());
}
That should do what you're seeking.
QStandardItemModel::clear()
Which clears all the items including the header rows.