在QTableView中选择行/行复制到QClipboard [英] selected Rows/Line in QTableView copy to QClipboard

查看:896
本文介绍了在QTableView中选择行/行复制到QClipboard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对不好的英语很抱歉。

First of all, sorry for bad English.

这是关于C ++和Qt。我有一个SQLite数据库,我做到了一个QSqlTableModel。
为了显示数据库,我把这个模型放到一个QTableView。

It's about C++ and Qt. 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.

但我没有想法如何做的选择-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.

你能帮我吗?

Berschi

推荐答案

要实际捕获选择,请使用项目视图的选择模型以获取索引列表。假设您有一个 QTableView * 调用查看,您可以这样选择:

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 。将数据转换为字符串(如果尚未)并将每个字符串连接在一起。然后,您可以使用 QClipboard.setText 将结果粘贴到剪贴板。请注意,对于Excel和Calc,每个列通过换行符(\\\
)与下一行分隔,每一行由制表符(\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(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);

警告:我没有机会尝试此代码,一个PyQt等效工程。

Warning: I have not had a chance to try this code, but a PyQt equivalent works.

这篇关于在QTableView中选择行/行复制到QClipboard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆