Qt?QTableWidget?實現(xiàn)行選中及行懸浮高亮效果
表格整行的 selected、hover 高亮需求很常見,但使用 Qt 提供的開箱即用的方法根本無法實現(xiàn)這個需求(至少在當(dāng)前的時間節(jié)點是不行的);想要實現(xiàn)這個效果必須要費一點點力氣,我們盡量選擇較為簡單的方法。
話不多說,先看效果圖:
實現(xiàn)的原理
經(jīng)常用 QWidgets 的朋友應(yīng)該都知道,框架中的 QTableWidget、QTreeWidget、QListWidget 等控件以及它們的基類 xxView 都是 MVD(model、view、delegate) 的結(jié)構(gòu),實現(xiàn)整行選中我們選擇子類化 QStyledItemDelegate 的方式,這個方法較為簡單,不會增加太多的心智負(fù)擔(dān),只需要以下幾個步驟:
- 創(chuàng)建一個類繼承于 QStyledItemDelegate
- 將外部將要使用這個 delegate 的 QTableWidget 傳入,這里我選擇了作為構(gòu)造函數(shù)的參數(shù),形式無所謂,只要確保在使用的時候此對象有效即可
- 重寫基類的 paint 函數(shù),客制化邏輯
- 創(chuàng)建對象,設(shè)置給 QTableWidget
頭文件
#include <QStyledItemDelegate> #include <QTableWidget> class HoveredRowItemDelegate : public QStyledItemDelegate { public: explicit HoveredRowItemDelegate(QTableWidget *parent = nullptr); protected: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: const QTableWidget *tableWidget{}; };
源文件
#include "hoveredrowitemdelegate.h" #include <QPainter> HoveredRowItemDelegate::HoveredRowItemDelegate(QTableWidget *parent) : QStyledItemDelegate{parent} { tableWidget = parent; } void HoveredRowItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { //選中狀態(tài)或是在鼠標(biāo)下方的狀態(tài) if(option.state.testFlag(QStyle::State_Selected) || option.state.testFlag(QStyle::State_MouseOver)) { QTableWidgetItem *hoveredItem = tableWidget->item(index.row(), index.column()); if(hoveredItem) { const int row = hoveredItem->row(); //遍歷列,繪制此行的所有列 for(int column = 0; column < tableWidget->columnCount(); column++) { QTableWidgetItem *item = tableWidget->item(row, column); if(item) { QModelIndex index = tableWidget->model()->index(row, column); QStyleOptionViewItem itemOption = option; itemOption.index = index; itemOption.rect = tableWidget->visualItemRect(item); QStyledItemDelegate::paint(painter, itemOption, index); } } } } else { return QStyledItemDelegate::paint(painter, option, index); } }
使用
auto delegate = new HoveredRowItemDelegate(ui->tableWidget); ui->tableWidget->setItemDelegate(delegate);
QTableWidget 設(shè)置下樣式表:
QTableView::item:hover { background-color: red; } QTableView::item:selected { background-color: blue; }
到此這篇關(guān)于Qt QTableWidget 實現(xiàn)行選中及行懸浮高亮效果的文章就介紹到這了,更多相關(guān)Qt QTableWidget 行懸浮高亮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ inline內(nèi)聯(lián)函數(shù)詳解
這篇文章主要介紹了C++ inline內(nèi)聯(lián)函數(shù)詳解,有感興趣的同學(xué)可以借鑒參考下2021-02-02C++實現(xiàn)LeetCode(82.移除有序鏈表中的重復(fù)項之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(82.移除有序鏈表中的重復(fù)項之二),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C語言完美實現(xiàn)動態(tài)數(shù)組代碼分享
本文給大家分享的是一則使用C語言實現(xiàn)動態(tài)數(shù)組的代碼,完美解決內(nèi)存溢出以及內(nèi)存回收問題,有需要的小伙伴可以參考下。2016-02-02C++實現(xiàn)猜數(shù)小游戲的實現(xiàn)
這篇文章主要介紹了C++實現(xiàn)猜數(shù)小游戲的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02