I have a SQLite-Database and I did it into a QSqlTableModel
.
To show the Database, I put that Model into a QTableView
.
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.
But I have no Idea what to do with the Selected
SIGNAL and the QModelIndex
and how to put this into the Clipboard.
I wrote some code based on some of the others' answers. I subclassed
QTableWidget
and overrodekeyPressEvent()
to allow the user to copy the selected rows to the clipboard by typing Control-C.Output example (tab-separated):
I finally got it, thanks.
and
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 *
calledview
you get the selection this way: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 useQClipboard.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.Warning: I have not had a chance to try this code, but a PyQt equivalent works.
Quark's answer (the selected one) is good for pointing people in the right direction, but his algorithm is entirely incorrect. In addition to an off by one error and incorrect assignment, its not even syntactically correct. Below is a working version that I just wrote and tested.
Let's assume our example table looks like so:
A | B | C
D | E | F
The problem with Quark's algorithm is the following:
If we replace his \t separator with a ' | ', it will produce this output:
B | C | D
E | F |
The off by one error is that D appears in the first row. The incorrect assignment is evidenced by the omission of A
The following algorithm corrects these two problems with correct syntax.
The reason I chose to use a counter instead of an iterator is just because it is easier to test if there exists another index by checking against the count. With an iterator, I suppose maybe you could just increment it and store it in a weak pointer to test if it is valid but just use a counter like I did above.
We need to check if the next line will be on on a new row. If we are on a new row and we check the previous row as Quark's algorithm does, its already too late to append. We could prepend, but then we have to keep track of the last string size. The above code will produce the following output from the example table:
A | B | C
D | E | F
I can't help but notice that you can simplify your code using a
foreach()
construct and theQStringList
class, which has a convenientjoin()
function.