How to move QListWidgetItem? - c++

How to move QListWidgetItem and do not miss Item widget?
This works when drag & drop but can't do the same job on button.

removeItemWidget( item(row) );
QCoreApplication::removePostedEvents (p_widget,QEvent::DeferredDelete );
I remove widget which is shown in Item and make a patch in the way that remove delete signal from queue. in this way I can move Widget to another item
int DropList::moveWidget(int row, int pos)
{
const int new_row = row+pos;
if(count()>1 && row>=0 && row <count() && new_row>=0 && new_row<count())
{
// A->B
DropListItem *pA = widgetByRow(row);
DropListItem *pB = widgetByRow(new_row);
if(pB->isMovable() && pA->isMovable())
{
removeItemWidget(item(new_row));
removeItemWidget(item(row));
QCoreApplication::removePostedEvents (pB,QEvent::DeferredDelete );
QCoreApplication::removePostedEvents (pA,QEvent::DeferredDelete );
setItemWidget(item(new_row),pA);
setItemWidget(item(row),pB);
}
emit changed();
return new_row;
}
return 0;
}
parameters are row - is an item row and pos +1, +2 ,-1 ,....

Related

Tab to next visible column in QTableView

I have a custom QTableView and QAbstractTableModel. My QTableView hides some of the columns from the QAbstractTableModel as they aren't needed.
When I hit Tab, I would like to select the next available (editable) column. My current implementation is to grab the next index from the QAbstractTableModel, but this index includes columns that are hidden. (So when hitting Tab it may be a couple presses before you see the "next" column selected.)
How can I tell Tab to jump to the next visible column?
The language is C++. Below is the code within my QTableView:
void keyPressEvent(QKeyEvent* event)
{
if((event->modifiers() == Qt::KeyboardModifier::NoModifier) && (event->key() == Qt::Key::Key_Tab))
{
this->moveToNextCell();
}
else
{
this->QTableView::keyPressEvent(event);
}
}
void moveToNextCell()
{
const QModelIndex index = this->currentIndex();
int nextColumn = index.column() + 1;
if(index.column() <= lastEditableCol)
{
this->setCurrentIndex(model->index(index.row(), nextColumn));
}
}
It's not elegant, but I've solved the problem by using isColumnHidden() from QTableView. I just iterate through the columns until I find one that isn't hidden.
for(int i = nextColumn; i <= numOfColumns && nextColumn <= numOfColumns; i++)
{
if(this->isColumnHidden(nextColumn) == true)
{
nextColumn += 1;
}
else
{
i = numOfCol + 1;
}
}

How to change button position in CMFCToolBar?

Can I change position of some button in CMFCToolBar ? For example set third button at begin of toolbar.
Just get the old button, insert it at the new position, delete the old one.
// Get button at position 3 and move it to position 1
auto *pButton = bar.Getbutton(2);
bar.InsertButton(*pButton,0);
bar.RemoveButton(2);
It is save to dereference the pointer because InsertButton creates a copy.
My version for few buttons:
// pIDs - array of buttons IDs
// nIDCounts - size of array
void ArrangeButtons(CMFCToolBar& wnd, const UINT* pIDs, UINT nIDCounts)
{
std::vector<std::unique_ptr<CMFCToolBarButton>> aBtns;
std::transform(pIDs, std::next(pIDs, nIDCounts), std::inserter(aBtns, std::end(aBtns)), [&](UINT nID)-> std::unique_ptr < CMFCToolBarButton > {
std::unique_ptr<CMFCToolBarButton> res;
CMFCToolBarButton* pBtn = wnd.GetButton(wnd.CommandToIndex(nID));
if ((pBtn != nullptr) && pBtn->IsKindOf(RUNTIME_CLASS(CMFCToolBarButton))) {
res.reset(STATIC_DOWNCAST(CMFCToolBarButton, pBtn->GetRuntimeClass()->CreateObject()));
res->CopyFrom(*pBtn);
}
return std::move(res);
});
wnd.RemoveAllButtons();
std::for_each(std::begin(aBtns), std::end(aBtns), [&](std::unique_ptr<CMFCToolBarButton>& btn) {
if (btn) {
wnd.InsertButton(*btn);
}
});
}

How to find the row from which drag has started QTableView

I was working on QTableView and I want to achieve drag and drop on it.
The way I want it is:
When I drag, I want to take out the row which is to be dragged and place an empty place holder there, this is how I have reimplemented dragEnterEvent:
void dragEnterEvent ( QDragEnterEvent * event )
{
if( event->source() == this )
{
// Get the row to be dragged
int mItemDraggedRowPosition = rowAt( event->pos().y() );
auto currentModel = model();
auto standardModel = boost::polymorphic_cast< QStandardItemModel *>( currentModel );
// Take out the dragged row
QList<QStandardItem *> mDraggedItem = standardModel->takeRow ( ( mItemDraggedRowPosition ) );
// Insert an empty row there
standardModel->insertRow( ( mItemDraggedRowPosition ), new QStandardItem() );
}
event->accept();
}
}
Now the problem I am facing here is the row number which I am getting is incorrect some times.
Am I not doing it correctly .?
Is there any alternative way to find out the row from which the drag was started,
seems like the way I am trying to get it:
int mItemDraggedRowPosition = rowAt( event->pos().y() );
does not return correct value always.
I finally reproduced problem and I got incorrect values too (drag very close to the joining area of 2 rows). So I solved this issue with next event filter:
ui->tableView->setDragEnabled(true);//somewhere in constructor
ui->tableView->setAcceptDrops(true);
//...
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->tableView->viewport() && event->type() == QEvent::DragEnter)
{
QDragEnterEvent * e = static_cast<QDragEnterEvent *>(event);
qDebug( ) << ui->tableView->rowAt(e->pos().y());
}
return QObject::eventFilter(obj, event);
}
To use eventFilter you should also:
protected:
bool eventFilter(QObject *obj, QEvent *event);//in header
and
qApp->installEventFilter(this);//in constructor
I finally ended up overriding "mousePressEvent" and saving the start position there.
I use the same saved position in "dragEnterEvent".
This one works perfectly for me.
void
PrePressView::TableWidget::mousePressEvent( QMouseEvent * inEvent )
{
if ( inEvent->button() == Qt::LeftButton )
{
int rowToMove = rowAt( inEvent->y() );
}
}

Add icon from array to QListWidget item

I've written a loop which adds some items to my QListWidget. Now I want them to have an icon from my qrc file. For this I would use a loop in which I add a unique icon to each item.
void Test::Query()
{
ui->listWidget_Available->clear();
QString CmdList[4] = {"kcmshell4 --list|grep -q kcm_grub2",
"kcmshell4 --list|grep -q kcm_networkmanagement",
"which pastebunz",
"[ -z $ink3_ver ]"};
QString NameList[4] = {"kcm_grub2",
"kcm_networkmanagement",
"pastebunz",
"Shellmenu"};
QString IconList[4] = {":/icons/icons/GNU.png",
":/icons/icons/networkmanager.png",
":/icons/icons/edit-paste.png",
":/icons/icons/menu.png"};
QIcon ItemIcon;
int iCntSize = sizeof(CmdList) / sizeof(CmdList[0]);
Next thing is to clear the List:
for(int iItem = 0; iItem < iCntSize; iItem++)
{
ui->listWidget_Available->addItem(NameList[iItem]);
ui->listWidget_Available->item(iItem)->setCheckState(Qt::PartiallyChecked);
}
Now the ugly part:
for(int iRow = 0; iRow < iCntSize; iRow++)
{
int BarValue = ui->progressBar->value();
ui->progressBar->setValue(BarValue+(100/iCntSize));
QString status = QString("Processing index %1 of %2. Name: %3").arg(iRow).arg(iCntSize).arg(NameList[iRow]);
qDebug() << status << (BarValue+25);
And here is my problem:
ItemIcon.addFile(IconList[iRow], QSize(), QIcon::Normal, QIcon::Off);
ui->listWidget_Available->item(iRow)->setIcon(ItemIcon); <--- how to do THIS?
How can I do this?
ui->textEdit_Informations->append("Searching for "+NameList[iRow]);
mProcess = new QProcess();
mProcess->start("/bin/bash", QStringList() << "-c" << QString(CmdList[iRow]));
mProcess->waitForFinished();
if ( mProcess->exitStatus() == QProcess::CrashExit )
{
ui->textEdit_Informations->setTextColor(Qt::red);
ui->textEdit_Informations->append("\t[FATAL]");
}
else if ( mProcess->exitCode() != 0 )
{
ui->textEdit_Informations->setTextColor(Qt::magenta);
ui->textEdit_Informations->append("\t[MISSED]");
ui->listWidget_Available->item(iRow)->setCheckState(Qt::Unchecked);
}
else if ( mProcess->exitCode() == 0 )
{
ui->textEdit_Informations->setTextColor(Qt::green);
ui->textEdit_Informations->append("\t[FOUND]");
ui->listWidget_Available->item(iRow)->setCheckState(Qt::Checked);
}
ui->textEdit_Informations->setTextColor(Qt::white);
}
}
Any suggestions?
You should use the constructor and a new QIcon each time instead of QIcon::addFile:
QIcon ItemIcon(IconList[iRow]);
ui->listWidget_Available->item(iRow)->setIcon(ItemIcon);
addFile would only be useful if you had a different image for each state of the item the icon is in (normal, activated, disabled, ...).

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