全部复制(不含标题):
void FormAssets_brow::setClipboard() { int rows=ui->tableWidget1->rowCount(); int column=ui->tableWidget1->columnCount(); QString str=""; for(int i=0; i<rows; i++) // 取出每个格子的内容 { for(int j=0; j<column; j++){ if(ui->tableWidget1->item(i,j) != NULL){//一定要先判断非空,否则会报错 str.append(ui->tableWidget1->item(i,j)->text()); str.append("\t"); }else{ str.append(""); //空字符弄成空格 str.append("\t"); } } str.append("\n"); } QClipboard *board = QApplication::clipboard(); board->setText(str); QMessageBox::information(NULL, "信息", "复制成功!"); }
选中复制:
QList<QTableWidgetItem*> tableWidgetItem = ui->tableWidget->selectedItems(); if(tableWidgetItem.count()==0) //如果没有选择,返回 return; //选择范围 int topRow ,buttomRow, leftColumn, rightColumn; QList<QTableWidgetSelectionRange> tableSelectRange= ui->tableWidget->selectedRanges(); for(int i=0;i<tableSelectRange.count();i++) { topRow= tableSelectRange.at(i).topRow(); buttomRow=tableSelectRange.at(i).bottomRow(); leftColumn=tableSelectRange.at(i).leftColumn(); rightColumn=tableSelectRange.at(i).rightColumn(); } //复制到cliptext QString clipText; for (int i=topRow;i<=buttomRow;i++) { for (int j=leftColumn;j<=rightColumn;j++) { QString text; if( ui->tableWidget->item(i,j)!=nullptr )//这个很重要 text = ui->tableWidget->item(i,j)->text(); clipText.append(text); clipText.append("\t"); } clipText.chop(1);//删除末尾一个字符 clipText.append("\n"); } QClipboard *clipboard = QApplication::clipboard();//复制到剪贴板,可以粘贴到excel clipboard->setText(clipText );
发表评论