QTableView多選

來源:互聯網
上載者:User

首先要瞭解它的setSelectionBehavior和setSelectionMode這兩個介面,接下來再來考慮選中的問題。查看官方文檔,setSelectionBehavior用來設定選中的是儲存格,行還是列,setSelectionMode用來設定使用者點擊後的介面響應:單選,多選,延伸選取(Ctrl+Shift鍵),相鄰,不選中。這裡僅介紹設定為ExtendedSelection mode後的多選問題。

當QTableView進行如下初始化後:

tableview->setSelectionBehavior(QAbstractItemView::SelectRows);tableview->setSelectionMode(QAbstractItemView::ExtendedSelection);

用代碼進行多選的時候,調用QTableView::selectRow或者tableview->selectionModel()->select都達不到我們的要求。

查看API,發現select有兩種用法:

virtual void select(const QModelIndex &index, QItemSelectionModel::SelectionFlags command);virtual void select(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command);

之前我們使用的是上面一種,沒錯下面的介面才是我們需要的。看起來不知道怎麼使用,下面是封裝後的方法:

void selectMulRows(const QModelIndexList &indexes){    QItemSelectionModel* selection_model = tableview_->selectionModel();    if (indexes.isEmpty() || !selection_model || !model_) {        return;    }    QItemSelection selection;    foreach(QModelIndex index, indexes) {        QModelIndex left = model_->index(index.row(), 0);        QModelIndex right = model_->index(index.row(), model_->columnCount() - 1);        QItemSelection sel(left, right);        //將每一個儲存格/每一行都作為一個QItemSelection 對象,並拼接到總的QItemSelection 對象中        selection.merge(sel, QItemSelectionModel::Select);    }    selection_model->select(selection, QItemSelectionModel::Select);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.