c++ - QTableView 中选中的行,复制到 QClipboard

标签 c++ qt qt4 clipboard qtableview

我有一个 SQLite 数据库,我把它做成了一个 QSqlTableModel。 为了显示数据库,我将该模型放入 QTableView

现在我想创建一个方法,将所选行(或整行)复制到 QClipboard 中。之后我想将它插入到我的 OpenOffice.Calc-Document 中。

但我不知道如何处理 Selected SIGNAL 和 QModelIndex 以及如何将其放入剪贴板。

最佳答案

要实际捕获选择,您可以使用项目 View 的 selection model获取 list of indices .假设您有一个名为 viewQTableView *,您可以通过以下方式获得选择:

QAbstractItemModel * model = view->model();
QItemSelectionModel * selection = view->selectionModel();
QModelIndexList indexes = selection->selectedIndexes();

然后循环遍历索引列表,在每个索引上调用 model->data(index)。如果尚未将数据转换为字符串并将每个字符串连接在一起。然后您可以使用 QClipboard.setText 将结果粘贴到剪贴板。请注意,对于 Excel 和 Calc,每一列由换行符 ("\n") 与下一列分隔,每一行由制表符 ("\t") 分隔。您必须检查索引以确定何时移动到下一行。

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

警告:我还没有机会尝试这段代码,但是 PyQt 等效的代码。

关于c++ - QTableView 中选中的行,复制到 QClipboard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230222/

相关文章:

c++ - 根据枚举值调用特定的模板函数

c++ - 带有 "%0*d"的 snprintf,参数太少

c++ - 在 boost 图库中为深度优先搜索提供颜色图时遇到问题

c++ - 生成的 Protobuf 代码使应用程序崩溃

python - 在 Python Qt 中访问自定义小部件?

python - 在 C++/Obj-C++ 中运行 Tensorflow 分类器模型导致与 Python 不同的结果

c++ - 在 aux 方法中创建的 QWidget 不显示/绘制

c++ - qt 5.0.1 mingw 32位问题

windows - 隐藏终端上打印的所有 QT 应用程序警告?

c++ - Qt4 DNS 代理 QUdpSocket