QTableView中的选定行,复制到QClipboard [英] Selected Rows in QTableView, copy to QClipboard
问题描述
我有一个SQLite数据库,并将它放入了 QSqlTableModel
中。
为了显示数据库,我将模型放入 QTableView
。
I have a SQLite-Database and I did it into a QSqlTableModel
.
To show the Database, I put that Model into a QTableView
.
现在我要创建一个方法,其中选定的行(或整行)将被复制到 QClipboard
中。之后,我要将其插入到OpenOffice.Calc文档中。
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.
但是我不知道如何处理 Selected
SIGNAL和 QModelIndex
以及如何将其放入剪贴板。
But I have no Idea what to do with the Selected
SIGNAL and the QModelIndex
and how to put this into the Clipboard.
推荐答案
要实际捕获选择,请使用项目视图的选择模型以获得索引列表。假设您有一个 QTableView *
称为 view
,则可以通过以下方式获得选择:
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();
然后遍历索引列表,调用 model-> data(index)
上的每个索引。如果尚未将数据转换为字符串,则将每个字符串连接在一起。然后,您可以使用 QClipboard.setText
将结果粘贴到剪贴板。请注意,对于Excel和Calc,每一列之间用换行符( \n)隔开,而每一行则用制表符( \t)隔开。您必须检查索引以确定何时移动到下一行。
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 ¤t, 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);
警告:我没有机会尝试这段代码,但是相当于PyQt的作品。
Warning: I have not had a chance to try this code, but a PyQt equivalent works.
这篇关于QTableView中的选定行,复制到QClipboard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!