gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:23:02 27 4
gpt4 key购买 nike

我有一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com