Reputation: 275
Is there a way to allow the header of a QTableView
to be copied to the clipboard?
I have a table created with QTableView
and QAbstractTableModel
. To enable rowd and columns selection, I add this line to the constructor of my QTableView
setSelectionMode(QAbstractItemView::ExtendedSelection);
And to copy the data table to the clipboard I implemented the following function in a class that inherits from QTableView
:
bool MyTableView::eventFilter(QObject * obj, QEvent * event) {
if(event->type() == QEvent::KeyPress ) {
auto* keyEvent = dynamic_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_C && (keyEvent->modifiers() == Qt::ControlModifier)) {
QModelIndexList cells = selectedIndexes();
std::sort(cells.begin(), cells.end()); // 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);
return true;
}
}
return QObject::eventFilter(obj, event);
}
The above function allows me to copy any cell/row and even column of a table. The only problem is that I can't copy a table header to the clipboard. Is there a way to make the header selectable and copyable?
In MyTableModel
class I implement the flags
function to select the table items.
Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const {
return QAbstractTableModel::flags(index) | Qt::ItemIsSelectable;
}
Any suggestion or idea?
Upvotes: 1
Views: 95
Reputation: 4743
You can use model()->headerData(column, Qt::Horizontal).toString()
to get header data, just collect list of column indexes from selectedIndexes
before itarating over data and call it for each item, appending result to text
.
To make header selectable you need to override default QHeaderView
behaviour, by default clicking on header section makes whole row or column selected.
Upvotes: 1