本人技術小白一枚,運用QT也有一段時間,其中遇到很多問題,也通過網上查閱找到很多解決辦法,但是感覺因為
版本問題導致解決方案很多,但是能解決實際問題的不容易,所以就把我工作中遇到的問題和對應版本進行統計,與大家共勉;希望各位大神多給意見;1、在進行運用Qt4.8.6的過程中,發現運用QTableWidget的selectItems()函數獲取的單元格不是從左向右排列的,而是從上往下重複的,這就造成在前面複製粘貼一章中的複製功能有缺陷,複製的內容沒有製表符;造成的結果是粘貼板上的字符串都是用"\n"來分割的,黏貼也只能黏貼一列;下面是該問題的解決辦法,運用的是selectedRanges()函數來處理的,默認的是選擇框為1;實測有效
<code>if
(this->objectName() =="actionCopy"
) { QString copied_text; QList itemRanges = table->selectedRanges();for
(int i = itemRanges.at(0
).topRow(); i <= itemRanges.at(0
).bottomRow(); i++) {for
(int j = itemRanges.at(0
).leftColumn();j<=itemRanges.at(0
).rightColumn();j++) {if
(j == itemRanges.at(0
).rightColumn()) { copied_text.append(table->item(i,j)->text()); }else
{ copied_text.append(table->item(i,j)->text()); copied_text.append("\t"
); } } copied_text.append("\n"
); } copied_text.append("\n"
); QApplication::clipboard()->setText(copied_text); }/<code>
2、QTableView的複製過程;
概述
粘貼板表格內容格式:
列與列之間內容以製表符分隔("\t")
行與行之間內容以換行符分隔("\n")
粘貼:
獲取粘貼板內容,把內容分解成單個item的值並放到表格中
通過QApplication::clipboard()->text()類獲取粘貼板的內容
複製:
獲取選中item,把選中item內容組織一下並放到粘貼板
通過QApplication::clipboard()->setText()設置粘貼板內容
<code>bool
MyTestTable:event(QEvent *event) {if
(event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent =static_cast
(event);if
(keyEvent->matches(QKeySequence::Paste)) { QString text_to_past = QApplication::clipboard()->text(); QStringList table_row_data_list = text_to_past.split("\n"
, QString::SkipEmptyParts); QModelIndex current_index =this
->currentIndex();for
(int
i =0
; ithis
->rowCount() - current_index.row() && i < table_row_data_list.length(); ++i){ QStringList row_data_list = table_row_data_list.at(i).split("\t"
);for
(int
k =0
; kthis
->columnCount() - current_index.column() && kthis->item(i+current_index.row(), k+current_index.column())->setText(row_data_list.at(k)); } } event->accept();return
true
; }else
if
(keyEvent->matches(QKeySequence::Copy)){ QString copied_text; QModelIndexList current_selected_indexs =this
->selectedIndexes();int
current_row = current_selected_indexs.at(0
).row();for
(int
i =0
; i < current_selected_indexs.count(); i++){if
(current_row != current_selected_indexs.at(i).row()){ current_row = current_selected_indexs.at(i).row(); copied_text.append("\n"
); copied_text.append(current_selected_indexs.at(i).data().toString());continue
; }if
(0
!= i){ copied_text.append("\t"
); } copied_text.append(current_selected_indexs.at(i).data().toString()); } copied_text.append("\n"
); QApplication::clipboard()->setText(copied_text); event->accept();return
true
; } }return
QTableView::event(event); }/<code>
3、QT4.8.6中QTreeWidget,QTableWidget的內容自適應,注意與QT5的內容自適應功能進行區分:
<code>ui->treeWidget->header()->setResizeMode(QHeaderView::ResizeToContents); ui->tableWidget->header()->setResizeMode(QHeaderView::ResizeToContents);/<code>