PDA

View Full Version : QTableWidget - Copy & Paste failed



rivci
28th December 2010, 05:14
Firstly, I am sorry for my poor english :)

Here I subclass QTableWidget and name it TabelJo. Next, I implement 2 functions, copy and paste. You can see the codes below.


void TabelJo::copy(){
QTableWidgetSelectionRange range = selectedRange();
QString str;
for (int i = 0; i < range.rowCount(); ++i) {
if (i > 0)
str += "\n";
for (int j = 0; j < range.columnCount(); ++j) {
if (j > 0)
str += "\t";
str += getText( range.topRow() + i, range.leftColumn() + j);
}
}
str += "\n";
QApplication::clipboard()->setText(str);
qDebug() << QApplication::clipboard()->text();
}

void TabelJo::paste(){
QString str = QApplication::clipboard()->text();
qDebug() << QApplication::clipboard()->text();
QStringList rows = str.split('\n');
int numRows = rows.count()-1;
int numColumns = rows.first().count('\t') + 1;

qDebug() << numRows << " " << numColumns ;
for (int i = 0; i < numRows; ++i) {
QStringList columns = rows[i].split('\t');
for (int j = 0; j < numColumns; ++j) {
setText(currentRow()+i,currentColumn()+j,columns[j],Qt::AlignLeft | Qt::AlignVCenter);
}
}
}

Consider I select these items on my table:
| a | a1 | a2 |
| b | b2 | b3 |
then I copy them.

The code on line 14 execute successfully.
Line 15 give this result:
"a a1 a2
b b2 b3
"
maybe this form will have a better look "a\ta1\ta2\nb\tb2\b3\n"

The problem is when I try to paste them, the code on line 20 only give this result:
"b3"

I use win7 and Qt 4.7.0 (32 bit)

Could anyone help me to solve this problem? I'm really stack here. :(

rivci
4th January 2011, 10:38
I just realize that QTableWidget has its default copy function (Ctrl+C). The next question is, how to overwrite this function?

Added after 1:

my bad :p



void TabelJo::keyPressEvent(QKeyEvent *event){
if( event==QKeySequence::Delete )
del();
else if( event->matches( QKeySequence::Copy ) )
copy();
else if( event->matches( QKeySequence::Paste ) )
paste();
QTableWidget::keyPressEvent(event);
}


I forget to place "else" at the last "if"
the code should be like this



void TabelJo::keyPressEvent(QKeyEvent *event){
if( event==QKeySequence::Delete )
del();
else if( event->matches( QKeySequence::Copy ) )
copy();
else if( event->matches( QKeySequence::Paste ) )
paste();
else
QTableWidget::keyPressEvent(event);
}