私は SQLite-Database を持っていて、それをQSqlTableModel
. データベースを表示するために、そのモデルをQTableView
.
ここで、選択した行 (または行全体) を にコピーするメソッドを作成したいと思いますQClipboard
。その後、それを OpenOffice.Calc-Document に挿入したいと思います。
Selected
しかし、シグナルをQModelIndex
どうするか、そしてこれをクリップボードに入れる方法がわかりません。
私は SQLite-Database を持っていて、それを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 と 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 ¤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 の拡張機能) を適応させることになりました。上記のクォークによって提供されたものに基づいて構築されたコードは次のとおりです。
qtablewigetwithcopypaste.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);
}
}
Quark の回答 (選択されたもの) は、人々を正しい方向に向けるのに適していますが、彼のアルゴリズムは完全に間違っています。1 つのエラーによるオフと不適切な割り当てに加えて、構文的にも正しくありません。以下は、私が書いてテストした作業バージョンです。
サンプル テーブルが次のようになっているとします。
あ | ビ | C
D | え | ふ
Quark のアルゴリズムの問題点は次のとおりです。
\tセパレーターを' |に置き換えると、' の場合、次の出力が生成されます:
B | シー | D
E | ふ |
1 つずれているのは、Dが最初の行に表示されることです。誤った割り当ては、 Aの省略によって証明されます。
次のアルゴリズムは、これら 2 つの問題を正しい構文で修正します。
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);
イテレータの代わりにカウンタを使用することにした理由は、カウントに対してチェックすることで、別のインデックスが存在するかどうかを簡単にテストできるからです。イテレーターを使用すると、それをインクリメントしてウィークポインターに格納して有効かどうかをテストできると思いますが、上記のようにカウンターを使用するだけです。
次の行が新しい行にあるかどうかを確認する必要があります。新しい行にいて、Quark のアルゴリズムのように前の行をチェックすると、追加するには既に遅すぎます。先頭に追加することもできますが、最後の文字列サイズを追跡する必要があります。上記のコードは、例のテーブルから次の出力を生成します。
あ | ビ | C
D | え | ふ
なんらかの理由で std::sort 関数にアクセスできませんでしたが、Corwin Joy のソリューションの適切な代替手段として、sort 関数を次のように置き換えることで実装できることがわかりました。
std::sort(indexes.begin(), indexes.end());
と
qSort(indexes);
これは次のように書くのと同じです:
qSort(indexes.begin(), indexes.end());
親切なコード担当者に感謝します!
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))
モデル内のテキスト データにアクセスし、そのテキストをQClipboard
.
モデル内のテキスト データにアクセスするには、 を使用しますQModelIndex::data()
。デフォルトの引数はQt::DisplayRole
、つまり表示されるテキストです。
テキストを取得したら、 を使用してそのテキストをクリップボードに渡しますQClipboard::setText()
。
最後の要素に注意してください。以下のことに注意してください。'removeFirst()'の後にインデックスが空になる場合があります。したがって、「current」は決して有効ではなく、model()-> data(current)では使用しないでください。
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());
私はついにそれを手に入れました、ありがとう。
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( ", " ) ) ;
}