order of selected rows/lines in QTableView's selectedItems - c++

I am using a QTableWidget and want to copy some cells to clipboard. It seems the QTableWidget only supports the selectedItems method.
For some reason I get the output as first column and then second column. Not: first row and then second row. This makes it somehow difficult to seperate the cols/rows. Do you know what went wrong? Thanks!
QList<QTableWidgetItem *> selectedCells(TableView->selectedItems());
QTableWidgetItem * item;
mCopyByteArray.clear();
foreach(item, selectedCells)
{
mCopyByteArray.append(item->text());
mCopyByteArray.append("\r\n");
}
When building it up:
TableView = new QTableWidget(); /* I know that name somehow is wrong ;) */
TableView->setColumnCount(2);
QStringList HHeaderList;
HHeaderList << "Computer name" << "ServiceTag";
TableView->setHorizontalHeaderLabels(HHeaderList);
TableView->verticalHeader()->setVisible(false);
TableView->setEditTriggers(QTableWidget::NoEditTriggers);
Any ideas? Thank you!

This algorithm I wrote should do the trick:
QList<QTableWidgetItem *> selectedCells(TableView->selectedItems());
mCopyByteArray.clear();
QString text;
int row_count = TableView->rowCount();
int column_count = TableView->columnCount();
for( int i = 0; i < row_count; i++ )
{
for( int j = 0; j < column_count; j++ )
{
text = selectedCells.at( i + j * row_count )->text();
mCopyByteArray.append( text );
mCopyByteArray.append( "\r\n" );
}
}

You can use QTableWidget::selectedRanges() instead. Small Example:
#include <QList>
#include <QTableWidget>
#include <QTableWidgetSelectionRange>
/...
// you can have more than one selected areas in the table. So you can have more then one
// selected ranges
QList <QTableWidgetSelectionRange*> selectRanges(TableView->selectedRanges());
for (int i =0; i != selectRanges.size(); ++i) {
QTableWidgetSelectionRange range = selectRanges.at(i);
int top = range.topRow();
int bottom = range.bottomRow();
for (int i = top; i <= bottom; ++i) {
QTableWidgetItem *item1 = TableView->itemAt(i, 0); //first column item
QTableWidgetItem *item2 = TableView->itemAt(i, 1); //second column item
// do desired stuff
}
}
Note: I amn't aware of performance issues for this approach. You can check it.

Not really an answer, but some more information that I found out:
It seems that the order in which the selected items are returned by the selectedItems() function is the order in which they were selected.
Moreover, if the selectionBehavior property of the QTableWidget is set to SelectRows, then the selected items are returned in the order in which the rows were selected. For example, for a 2x3 table, where the rows are numbered 'A', 'B' and the columns are numbered '1', '2', '3': if you select B2 and then A1, then the selected items are returned as: B1,B2,B3,A1,A2,A3.

Related

QtableView and model in an infinite while loop

I have a QTableview I have a model attached to it. I have a infinite while loop in which I send and receive messages from a server. When I receive a message, I want to add a row to my table.
My problem is that I can't get this idea work. When I do while (true) it doesn't work.
i would be appriciate it if someone could help me.
Here is the piece of code that I am talking about:
model = new QStandardItemModel(4,1,this);
ui->tableView->setModel(model);
ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
while (true)
{
// Server response
reciever_input.wait_for_recieve();
std::vector<std::string> res = decode_msg(_serverResponse.front());
unsigned int it;
it = 8;
if (res[0] == "Y")
{
int row = 0;
//here I want to add rows in my table
for (; it < res.size(); it++, row++)
{
std::string temp = res[it]; // this is the string that I want to add
QString qtemp = QString::fromUtf8(temp.c_str());
QModelIndex index = model->index(row,0,QModelIndex());
model->setData(index,qtemp);
}
}
if (res[0] == "L")
break;
}
Have you tried to make a neu Thread for the server connection? I think you should run it as a second thread in the background and in case of neu datas update your model.
you can find qt doc here
you can also find also good examples in youtube
additional idea:
MarKS has right, something is missing in your code. Use this code to insert row at the end of model:
int rowNr;
rowNr = model->rowCount();
model->insertRow(rowNr); //insert new row
model->setData(model->index(rowNr, 1), qtemp ); //in Column 1 - your string qtemp
model->submitAll(); //to hand over
You are missing insertRow() inside your for loop. Please read through the documentation here.
I haven't tested the code myself, but it should look something similar to the code below:
while (true)
{
// Server response
reciever_input.wait_for_recieve();
std::vector<std::string> res = decode_msg(_serverResponse.front());
unsigned int it;
it = 8;
if (res[0] == "Y")
{
int row = 0;
//here I want to add rows in my table
for (; it < res.size(); it++, row++)
{
std::string temp = res[it]; // this is the string that I want to add
QString qtemp = QString::fromUtf8(temp.c_str());
// insert row into the model
model->insertRow(row, new QStandardItem(qtemp));
}
}
if (res[0] == "L")
break;
}
EDIT 1:
Setting int row = 0 will overwrite the rows every time you receive a new std::vector<std::string>. It is upto you how you want to use this piece of code.

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));

How to get list of selected rows during multiple selection in Qtableview?

I have the data in Qtableview, where my task is, when ever I do multiple selection of rows I want the content of all selected rows. or at least I would like to know what are the row numbers I have selected.
For this I have written code which is giving 'Zero' every time even though I don't select any row.
ui->xvalue->setSelectionMode(QAbstractItemView::ExtendedSelection);
ui->xvalue->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->xvalue->show();
QModelIndexList indexList = ui->xvalue->selectionModel()->selectedIndexes();
int row;
foreach (QModelIndex index, indexList) {
row = index.row();
}
printf("\n%d\n",row);
I even tried this but no use I am not getting the answer
QItemSelectionModel* selectionModel = this-> ui->xvalue->selectionModel();
QModelIndexList selected = selectionModel->selectedIndexes();
int num;
for(int i= 0; i< selected.count();i++)
{
QModelIndex index = selected.at(i);
qDebug() << index.row();
num = index.row();
printf("selected row is %d", num);
}

QTableWidget - setCellWidget missing addition?

I am just trying to add widgets into my table widget and I am trying the code below but all the time I run the program, the first widget is added but the rest is not added. Can you please help me for this situation ?
if(req.at(index).request.CodedValue.size() > 1 )
{
int rowNumber = -1;
for ( int paramNumber = 0 ; paramNumber < req.at(index).request.params.size(); paramNumber++)
{
if(req[index].request.params[paramNumber].semantic == "DATA")
{
rowNumber++;
QComboBox* reqComboBox = new QComboBox();
QLineEdit* tableReqLineEdit = new QLineEdit();
for ( int codedCounter = 0; codedCounter < req.at(index).request.CodedValue.at(paramNumber).trams.size(); codedCounter++)
{
// you should look for the subfunctions and add according to them
reqComboBox->addItem((req[index].request.CodedValue[paramNumber].trams[codedCounter].valueName));
QObject::connect(reqComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_tableCombobox_currentIndex());
}
ui.tableWidget->setCellWidget(rowNumber,1,reqComboBox);
}
}
}
Use qDebug in order to see how many times the for loop is executed. Probably it is executed only once:
#include <QDebug>
...
rowNumber++;
qDebug() << rowNumber;
...
Try the following:
for (int i=0; i<ui.tableWidget->rowCount(); i++)
{
ui.tableWidget->setCellWidget(i,1,new QLineEdit);
}
How many line edits do you see?
Notice that you should use the setRowCount in order to set the number of rows of your table widget.

Selected Rows in QTableView, copy to QClipboard

I have a SQLite-Database and I did it into a QSqlTableModel.
To show the Database, I put that Model into a QTableView.
Now I want to create a Method where the selected Rows (or the whole Line) will be copied into the QClipboard. After that I want to insert it into my OpenOffice.Calc-Document.
But I have no Idea what to do with the Selected SIGNAL and the QModelIndex and how to put this into the Clipboard.
To actually capture the selection you use the item view's selection model to get a list of indices. Given that you have a QTableView * called view you get the selection this way:
QAbstractItemModel * model = view->model();
QItemSelectionModel * selection = view->selectionModel();
QModelIndexList indexes = selection->selectedIndexes();
Then loop through the index list calling model->data(index) on each index. Convert the data to a string if it isn't already and concatenate each string together. Then you can use QClipboard.setText to paste the result to the clipboard. Note that, for Excel and Calc, each column is separated from the next by a newline ("\n") and each row is separated by a tab ("\t"). You have to check the indices to determine when you move to the next row.
QString selected_text;
// You need a pair of indexes to find the row changes
QModelIndex previous = indexes.first();
indexes.removeFirst();
foreach(const QModelIndex &current, indexes)
{
QVariant data = model->data(current);
QString text = data.toString();
// At this point `text` contains the text in one cell
selected_text.append(text);
// If you are at the start of the row the row number of the previous index
// isn't the same. Text is followed by a row separator, which is a newline.
if (current.row() != previous.row())
{
selected_text.append('\n');
}
// Otherwise it's the same row, so append a column separator, which is a tab.
else
{
selected_text.append('\t');
}
previous = current;
}
QApplication.clipboard().setText(selected_text);
Warning: I have not had a chance to try this code, but a PyQt equivalent works.
I had a similar problem and ended up adapting QTableWidget (which is an extension of QTableView) to add copy/paste functionality. Here is the code which builds on what was provided by quark above:
qtablewidgetwithcopypaste.h
// QTableWidget with support for copy and paste added
// Here copy and paste can copy/paste the entire grid of cells
#ifndef QTABLEWIDGETWITHCOPYPASTE_H
#define QTABLEWIDGETWITHCOPYPASTE_H
#include <QTableWidget>
#include <QKeyEvent>
#include <QWidget>
class QTableWidgetWithCopyPaste : public QTableWidget
{
Q_OBJECT
public:
QTableWidgetWithCopyPaste(int rows, int columns, QWidget *parent = 0) :
QTableWidget(rows, columns, parent)
{}
QTableWidgetWithCopyPaste(QWidget *parent = 0) :
QTableWidget(parent)
{}
private:
void copy();
void paste();
public slots:
void keyPressEvent(QKeyEvent * event);
};
#endif // QTABLEWIDGETWITHCOPYPASTE_H
qtablewidgetwithcopypaste.cpp
#include "qtablewidgetwithcopypaste.h"
#include <QApplication>
#include <QMessageBox>
#include <QClipboard>
#include <QMimeData>
void QTableWidgetWithCopyPaste::copy()
{
QItemSelectionModel * selection = selectionModel();
QModelIndexList indexes = selection->selectedIndexes();
if(indexes.size() < 1)
return;
// QModelIndex::operator < sorts first by row, then by column.
// this is what we need
// std::sort(indexes.begin(), indexes.end());
qSort(indexes);
// You need a pair of indexes to find the row changes
QModelIndex previous = indexes.first();
indexes.removeFirst();
QString selected_text_as_html;
QString selected_text;
selected_text_as_html.prepend("<html><style>br{mso-data-placement:same-cell;}</style><table><tr><td>");
QModelIndex current;
Q_FOREACH(current, indexes)
{
QVariant data = model()->data(previous);
QString text = data.toString();
selected_text.append(text);
text.replace("\n","<br>");
// At this point `text` contains the text in one cell
selected_text_as_html.append(text);
// If you are at the start of the row the row number of the previous index
// isn't the same. Text is followed by a row separator, which is a newline.
if (current.row() != previous.row())
{
selected_text_as_html.append("</td></tr><tr><td>");
selected_text.append(QLatin1Char('\n'));
}
// Otherwise it's the same row, so append a column separator, which is a tab.
else
{
selected_text_as_html.append("</td><td>");
selected_text.append(QLatin1Char('\t'));
}
previous = current;
}
// add last element
selected_text_as_html.append(model()->data(current).toString());
selected_text.append(model()->data(current).toString());
selected_text_as_html.append("</td></tr>");
QMimeData * md = new QMimeData;
md->setHtml(selected_text_as_html);
// qApp->clipboard()->setText(selected_text);
md->setText(selected_text);
qApp->clipboard()->setMimeData(md);
// selected_text.append(QLatin1Char('\n'));
// qApp->clipboard()->setText(selected_text);
}
void QTableWidgetWithCopyPaste::paste()
{
if(qApp->clipboard()->mimeData()->hasHtml())
{
// TODO, parse the html data
}
else
{
QString selected_text = qApp->clipboard()->text();
QStringList cells = selected_text.split(QRegExp(QLatin1String("\\n|\\t")));
while(!cells.empty() && cells.back().size() == 0)
{
cells.pop_back(); // strip empty trailing tokens
}
int rows = selected_text.count(QLatin1Char('\n'));
int cols = cells.size() / rows;
if(cells.size() % rows != 0)
{
// error, uneven number of columns, probably bad data
QMessageBox::critical(this, tr("Error"),
tr("Invalid clipboard data, unable to perform paste operation."));
return;
}
if(cols != columnCount())
{
// error, clipboard does not match current number of columns
QMessageBox::critical(this, tr("Error"),
tr("Invalid clipboard data, incorrect number of columns."));
return;
}
// don't clear the grid, we want to keep any existing headers
setRowCount(rows);
// setColumnCount(cols);
int cell = 0;
for(int row=0; row < rows; ++row)
{
for(int col=0; col < cols; ++col, ++cell)
{
QTableWidgetItem *newItem = new QTableWidgetItem(cells[cell]);
setItem(row, col, newItem);
}
}
}
}
void QTableWidgetWithCopyPaste::keyPressEvent(QKeyEvent * event)
{
if(event->matches(QKeySequence::Copy) )
{
copy();
}
else if(event->matches(QKeySequence::Paste) )
{
paste();
}
else
{
QTableWidget::keyPressEvent(event);
}
}
Quark's answer (the selected one) is good for pointing people in the right direction, but his algorithm is entirely incorrect. In addition to an off by one error and incorrect assignment, its not even syntactically correct. Below is a working version that I just wrote and tested.
Let's assume our example table looks like so:
A | B | C
D | E | F
The problem with Quark's algorithm is the following:
If we replace his \t separator with a ' | ', it will produce this output:
B | C | D
E | F |
The off by one error is that D appears in the first row. The incorrect assignment is evidenced by the omission of A
The following algorithm corrects these two problems with correct syntax.
QString clipboardString;
QModelIndexList selectedIndexes = view->selectionModel()->selectedIndexes();
for (int i = 0; i < selectedIndexes.count(); ++i)
{
QModelIndex current = selectedIndexes[i];
QString displayText = current.data(Qt::DisplayRole).toString();
// If there exists another column beyond this one.
if (i + 1 < selectedIndexes.count())
{
QModelIndex next = selectedIndexes[i+1];
// If the column is on different row, the clipboard should take note.
if (next.row() != current.row())
{
displayText.append("\n");
}
else
{
// Otherwise append a column separator.
displayText.append(" | ");
}
}
clipboardString.append(displayText);
}
QApplication::clipboard()->setText(clipboardString);
The reason I chose to use a counter instead of an iterator is just because it is easier to test if there exists another index by checking against the count. With an iterator, I suppose maybe you could just increment it and store it in a weak pointer to test if it is valid but just use a counter like I did above.
We need to check if the next line will be on on a new row. If we are on a new row and we check the previous row as Quark's algorithm does, its already too late to append. We could prepend, but then we have to keep track of the last string size. The above code will produce the following output from the example table:
A | B | C
D | E | F
For whatever reason I didn't have access to the std::sort function, however I did find that as a neat alternative to Corwin Joy's solution, the sort function can be implemented by replacing
std::sort(indexes.begin(), indexes.end());
with
qSort(indexes);
This is the same as writing:
qSort(indexes.begin(), indexes.end());
Thanks for your helpful code guys!
I wrote some code based on some of the others' answers. I subclassed QTableWidget and overrode keyPressEvent() to allow the user to copy the selected rows to the clipboard by typing Control-C.
void MyTableWidget::keyPressEvent(QKeyEvent* event) {
// If Ctrl-C typed
if (event->key() == Qt::Key_C && (event->modifiers() & Qt::ControlModifier))
{
QModelIndexList cells = selectedIndexes();
qSort(cells); // Necessary, otherwise they are in column order
QString text;
int currentRow = 0; // To determine when to insert newlines
foreach (const QModelIndex& cell, cells) {
if (text.length() == 0) {
// First item
} else if (cell.row() != currentRow) {
// New row
text += '\n';
} else {
// Next cell
text += '\t';
}
currentRow = cell.row();
text += cell.data().toString();
}
QApplication::clipboard()->setText(text);
}
}
Output example (tab-separated):
foo bar baz qux
bar baz qux foo
baz qux foo bar
qux foo bar baz
What you'll need to do is access the text data in the model, then pass that text to the QClipboard.
To access the text data in the model, use QModelIndex::data(). The default argument is Qt::DisplayRole, i.e. the displayed text.
Once you've retrieved the text, pass that text to the clipboard using QClipboard::setText().
a pyqt py2.x example:
selection = self.table.selectionModel() #self.table = QAbstractItemView
indexes = selection.selectedIndexes()
columns = indexes[-1].column() - indexes[0].column() + 1
rows = len(indexes) / columns
textTable = [[""] * columns for i in xrange(rows)]
for i, index in enumerate(indexes):
textTable[i % rows][i / rows] = unicode(self.model.data(index).toString()) #self.model = QAbstractItemModel
return "\n".join(("\t".join(i) for i in textTable))
I finally got it, thanks.
void Widget::copy() {
QItemSelectionModel *selectionM = tableView->selectionModel();
QModelIndexList selectionL = selectionM->selectedIndexes();
selectionL.takeFirst(); // ID, not necessary
QString *selectionS = new QString(model->data(selectionL.takeFirst()).toString());
selectionS->append(", ");
selectionS->append(model->data(selectionL.takeFirst()).toString());
selectionS->append(", ");
selectionS->append(model->data(selectionL.takeFirst()).toString());
selectionS->append(", ");
selectionS->append(model->data(selectionL.takeFirst()).toString());
clipboard->setText(*selectionS);
}
and
connect (tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(copy()));
I can't help but notice that you can simplify your code using a foreach() construct and the QStringList class, which has a convenient join() function.
void Widget::copy()
{
QStringList list ;
foreach ( const QModelIndex& index, tableView->selectedIndexes() )
{
list << index.data() ;
}
clipboard->setText( list.join( ", " ) ) ;
}
Careful with the last element. Note below, indexes may become empty after 'removeFirst()'. Thus, 'current' is never valid and should not be used in model()->data(current).
indexes.removeFirst();
QString selected_text;
QModelIndex current;
Q_FOREACH(current, indexes)
{
.
.
.
}
// add last element
selected_text.append(model()->data(current).toString());
Consider
QModelIndex last = indexes.last();
indexes.removeFirst();
QString selected_text;
Q_FOREACH(QModelIndex current, indexes)
{
.
.
.
}
// add last element
selected_text.append(model()->data(last).toString());
Here is a variation on what Corwin Joy posted that works with QTableView and handles sparse selections differently. With this code if you have different columns selected in different rows (e.g. selected cells are (1,1), (1, 2), (2, 1), (3,2)) then when you paste it you will get empty cells corresponding to the "holes" in your selection (e.g. cells (2,2) and (3,1)). It also pulls in the column header text for columns that intersect the selection.
void CopyableTableView::copy()
{
QItemSelectionModel *selection = selectionModel();
QModelIndexList indices = selection->selectedIndexes();
if(indices.isEmpty())
return;
QMap<int, bool> selectedColumnsMap;
foreach (QModelIndex current, indices) {
selectedColumnsMap[current.column()] = true;
}
QList<int> selectedColumns = selectedColumnsMap.uniqueKeys();
int minCol = selectedColumns.first();
// prepend headers for selected columns
QString selectedText;
foreach (int column, selectedColumns) {
selectedText += model()->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
if (column != selectedColumns.last())
selectedText += QLatin1Char('\t');
}
selectedText += QLatin1Char('\n');
// QModelIndex::operator < sorts first by row, then by column.
// this is what we need
qSort(indices);
int lastRow = indices.first().row();
int lastColumn = minCol;
foreach (QModelIndex current, indices) {
if (current.row() != lastRow) {
selectedText += QLatin1Char('\n');
lastColumn = minCol;
lastRow = current.row();
}
if (current.column() != lastColumn) {
for (int i = 0; i < current.column() - lastColumn; ++i)
selectedText += QLatin1Char('\t');
lastColumn = current.column();
}
selectedText += model()->data(current).toString();
}
selectedText += QLatin1Char('\n');
QApplication::clipboard()->setText(selectedText);
}
If anybody is interested, this web page provide a working code project on this topic, it's working pretty well.
Copy / paste functionality implementation for QAbstractTableModel / QTableView