QTableView中选定的行,复制到QClipboard
-
22-07-2019 - |
题
我有一个 SQLite 数据库,我把它变成了 QSqlTableModel
。为了显示数据库,我将该模型放入 QTableView
.
现在我想创建一个方法,其中选定的行(或整行)将被复制到 QClipboard
. 。之后我想将其插入到我的 OpenOffice.Calc-Document 中。
但我不知道该怎么办 Selected
信号和 QModelIndex
以及如何将其放入剪贴板。
解决方案
要实际拍摄使用项目视图的选择模型一选择>获得列表的索引的。假设你有一个名为QTableView *
view
你选择这种方式:
QAbstractItemModel * model = view->model();
QItemSelectionModel * selection = view->selectionModel();
QModelIndexList indexes = selection->selectedIndexes();
然后通过索引列表调用每个索引model->data(index)
循环。将数据转换为字符串,如果它是不是已经和串联在一起,每串。然后你可以使用QClipboard.setText
粘贴的结果到剪贴板。需要注意的是,对于Excel和计算值,各列从下一一个换行(“\ 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 ¤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的等效作品
其他提示
我有类似的问题,并最终适应QTableWidget的(这是QTableView中的扩展)来添加复制/粘贴功能。这里是一个建立在什么是由夸克上面提供的代码:
qtablewidgetwithcopypaste.h
// QTableWidget with support for copy and paste added
// Here copy and paste can copy/paste the entire grid of cells
#ifndef QTABLEWIDGETWITHCOPYPASTE_H
#define QTABLEWIDGETWITHCOPYPASTE_H
#include <QTableWidget>
#include <QKeyEvent>
#include <QWidget>
class QTableWidgetWithCopyPaste : public QTableWidget
{
Q_OBJECT
public:
QTableWidgetWithCopyPaste(int rows, int columns, QWidget *parent = 0) :
QTableWidget(rows, columns, parent)
{}
QTableWidgetWithCopyPaste(QWidget *parent = 0) :
QTableWidget(parent)
{}
private:
void copy();
void paste();
public slots:
void keyPressEvent(QKeyEvent * event);
};
#endif // QTABLEWIDGETWITHCOPYPASTE_H
qtablewidgetwithcopypaste.cpp
#include "qtablewidgetwithcopypaste.h"
#include <QApplication>
#include <QMessageBox>
#include <QClipboard>
#include <QMimeData>
void QTableWidgetWithCopyPaste::copy()
{
QItemSelectionModel * selection = selectionModel();
QModelIndexList indexes = selection->selectedIndexes();
if(indexes.size() < 1)
return;
// QModelIndex::operator < sorts first by row, then by column.
// this is what we need
// std::sort(indexes.begin(), indexes.end());
qSort(indexes);
// You need a pair of indexes to find the row changes
QModelIndex previous = indexes.first();
indexes.removeFirst();
QString selected_text_as_html;
QString selected_text;
selected_text_as_html.prepend("<html><style>br{mso-data-placement:same-cell;}</style><table><tr><td>");
QModelIndex current;
Q_FOREACH(current, indexes)
{
QVariant data = model()->data(previous);
QString text = data.toString();
selected_text.append(text);
text.replace("\n","<br>");
// At this point `text` contains the text in one cell
selected_text_as_html.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_as_html.append("</td></tr><tr><td>");
selected_text.append(QLatin1Char('\n'));
}
// Otherwise it's the same row, so append a column separator, which is a tab.
else
{
selected_text_as_html.append("</td><td>");
selected_text.append(QLatin1Char('\t'));
}
previous = current;
}
// add last element
selected_text_as_html.append(model()->data(current).toString());
selected_text.append(model()->data(current).toString());
selected_text_as_html.append("</td></tr>");
QMimeData * md = new QMimeData;
md->setHtml(selected_text_as_html);
// qApp->clipboard()->setText(selected_text);
md->setText(selected_text);
qApp->clipboard()->setMimeData(md);
// selected_text.append(QLatin1Char('\n'));
// qApp->clipboard()->setText(selected_text);
}
void QTableWidgetWithCopyPaste::paste()
{
if(qApp->clipboard()->mimeData()->hasHtml())
{
// TODO, parse the html data
}
else
{
QString selected_text = qApp->clipboard()->text();
QStringList cells = selected_text.split(QRegExp(QLatin1String("\\n|\\t")));
while(!cells.empty() && cells.back().size() == 0)
{
cells.pop_back(); // strip empty trailing tokens
}
int rows = selected_text.count(QLatin1Char('\n'));
int cols = cells.size() / rows;
if(cells.size() % rows != 0)
{
// error, uneven number of columns, probably bad data
QMessageBox::critical(this, tr("Error"),
tr("Invalid clipboard data, unable to perform paste operation."));
return;
}
if(cols != columnCount())
{
// error, clipboard does not match current number of columns
QMessageBox::critical(this, tr("Error"),
tr("Invalid clipboard data, incorrect number of columns."));
return;
}
// don't clear the grid, we want to keep any existing headers
setRowCount(rows);
// setColumnCount(cols);
int cell = 0;
for(int row=0; row < rows; ++row)
{
for(int col=0; col < cols; ++col, ++cell)
{
QTableWidgetItem *newItem = new QTableWidgetItem(cells[cell]);
setItem(row, col, newItem);
}
}
}
}
void QTableWidgetWithCopyPaste::keyPressEvent(QKeyEvent * event)
{
if(event->matches(QKeySequence::Copy) )
{
copy();
}
else if(event->matches(QKeySequence::Paste) )
{
paste();
}
else
{
QTableWidget::keyPressEvent(event);
}
}
夸克的回答(选择一个)是很好的人指点的方向是正确的,但他的算法是完全不正确。除了由一个错误和不正确的分配,它甚至没有语法正确关闭。下面是一个工作版本,我只是写和测试。
让我们假设我们的示例表看起来像这样:
:一种| C | ç结果 d | E | ˚F强>
与夸克的算法的问题是以下内容:
如果我们用取代他的 \吨强>分离器的” | “下,就会产生这样的输出:结果 的乙| ç| d点击 E | F | 强>
由一个错误的关是的 d 强>出现的第一排。不正确的分配由遗漏证明的 A 强>
下面的算法来校正这两个问题与正确的语法。
QString clipboardString;
QModelIndexList selectedIndexes = view->selectionModel()->selectedIndexes();
for (int i = 0; i < selectedIndexes.count(); ++i)
{
QModelIndex current = selectedIndexes[i];
QString displayText = current.data(Qt::DisplayRole).toString();
// If there exists another column beyond this one.
if (i + 1 < selectedIndexes.count())
{
QModelIndex next = selectedIndexes[i+1];
// If the column is on different row, the clipboard should take note.
if (next.row() != current.row())
{
displayText.append("\n");
}
else
{
// Otherwise append a column separator.
displayText.append(" | ");
}
}
clipboardString.append(displayText);
}
QApplication::clipboard()->setText(clipboardString);
我选择使用一个计数器来代替一个迭代的原因是,只是因为它是更容易测试,如果存在通过针对计数检查另一个索引。随着迭代器,我想也许你可以只增加它并将其存储在一个弱指针,以测试它是否有效,但只使用一个计数器像我上面那样。
我们需要检查的下一步线将上一个新行。如果我们是一个新的行,我们检查上一行的夸克的算法的确,它已经来不及追加。我们可以预先准备,但我们必须跟踪最后一个字符串的大小。上面的代码将产生从例如表下面的输出:
:一种| C | ç强>结果 的 d | E | ˚F强>
无论出于何种原因,我没有进入的std ::排序功能,但是我确实发现作为一个整洁的替代考文乐的解决方案,排序功能,可以通过替换实施
std::sort(indexes.begin(), indexes.end());
与
qSort(indexes);
这是相同的文字:
qSort(indexes.begin(), indexes.end());
感谢您有用的代码的家伙!
什么你需要做的是访问文本数据模型,然后该文本传递给的 QClipboard
。
要访问该模型中的文本数据,使用 QModelIndex::data()
。默认参数是Qt::DisplayRole
,即所显示的文本。
一旦检索的文本,用传递文本复制到剪贴板 QClipboard::setText()
一个PyQt的py2.x示例:
selection = self.table.selectionModel() #self.table = QAbstractItemView
indexes = selection.selectedIndexes()
columns = indexes[-1].column() - indexes[0].column() + 1
rows = len(indexes) / columns
textTable = [[""] * columns for i in xrange(rows)]
for i, index in enumerate(indexes):
textTable[i % rows][i / rows] = unicode(self.model.data(index).toString()) #self.model = QAbstractItemModel
return "\n".join(("\t".join(i) for i in textTable))
我写了基于一些别人的答案的一些代码。余子类QTableWidget
和压倒keyPressEvent()
以允许用户通过键入控制-C所选行复制到剪贴板。
void MyTableWidget::keyPressEvent(QKeyEvent* event) {
// If Ctrl-C typed
if (event->key() == Qt::Key_C && (event->modifiers() & Qt::ControlModifier))
{
QModelIndexList cells = selectedIndexes();
qSort(cells); // 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);
}
}
输出实例(制表符分隔):
foo bar baz qux
bar baz qux foo
baz qux foo bar
qux foo bar baz
我终于明白了,谢谢!
void Widget::copy() {
QItemSelectionModel *selectionM = tableView->selectionModel();
QModelIndexList selectionL = selectionM->selectedIndexes();
selectionL.takeFirst(); // ID, not necessary
QString *selectionS = new QString(model->data(selectionL.takeFirst()).toString());
selectionS->append(", ");
selectionS->append(model->data(selectionL.takeFirst()).toString());
selectionS->append(", ");
selectionS->append(model->data(selectionL.takeFirst()).toString());
selectionS->append(", ");
selectionS->append(model->data(selectionL.takeFirst()).toString());
clipboard->setText(*selectionS);
}
和
connect (tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(copy()));
我不禁注意到你可以使用简化你的代码 foreach()
构造和 QStringList
类,其中有一个方便的 join()
功能。
void Widget::copy()
{
QStringList list ;
foreach ( const QModelIndex& index, tableView->selectedIndexes() )
{
list << index.data() ;
}
clipboard->setText( list.join( ", " ) ) ;
}
小心的最后一个元素。下面的注释,索引可能变成空后“removeFirst()”。因此,“当前”是从来没有有效,不应该在模型中使用() - >数据(当前)
indexes.removeFirst();
QString selected_text;
QModelIndex current;
Q_FOREACH(current, indexes)
{
.
.
.
}
// add last element
selected_text.append(model()->data(current).toString());
考虑
QModelIndex last = indexes.last();
indexes.removeFirst();
QString selected_text;
Q_FOREACH(QModelIndex current, indexes)
{
.
.
.
}
// add last element
selected_text.append(model()->data(last).toString());
下面是与QTableView中的作品和不同的方式处理稀疏选择什么科温喜贴的变化。有了这个代码,如果你有不同的行中选择不同的列(1如选择细胞是(1,1),(1,2),(2,1),(3,2)),那么当您粘贴它,你会得到空对应于选择了“洞”细胞(EG细胞(2,2)和(3,1))。它还引入了列标题文本相交的选择列。
void CopyableTableView::copy()
{
QItemSelectionModel *selection = selectionModel();
QModelIndexList indices = selection->selectedIndexes();
if(indices.isEmpty())
return;
QMap<int, bool> selectedColumnsMap;
foreach (QModelIndex current, indices) {
selectedColumnsMap[current.column()] = true;
}
QList<int> selectedColumns = selectedColumnsMap.uniqueKeys();
int minCol = selectedColumns.first();
// prepend headers for selected columns
QString selectedText;
foreach (int column, selectedColumns) {
selectedText += model()->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
if (column != selectedColumns.last())
selectedText += QLatin1Char('\t');
}
selectedText += QLatin1Char('\n');
// QModelIndex::operator < sorts first by row, then by column.
// this is what we need
qSort(indices);
int lastRow = indices.first().row();
int lastColumn = minCol;
foreach (QModelIndex current, indices) {
if (current.row() != lastRow) {
selectedText += QLatin1Char('\n');
lastColumn = minCol;
lastRow = current.row();
}
if (current.column() != lastColumn) {
for (int i = 0; i < current.column() - lastColumn; ++i)
selectedText += QLatin1Char('\t');
lastColumn = current.column();
}
selectedText += model()->data(current).toString();
}
selectedText += QLatin1Char('\n');
QApplication::clipboard()->setText(selectedText);
}