//不解释,自己看。不保证完整,仅供思路参考#include QtGui/QApplication#include TableView.h#include QStandardItem#include QStandardItemModel int main(int argc, char *argv[]){ QApplication a(argc, argv); QStandardItemModel model; for ( int col = 0; col 3; col++ ) { QListQStandardItem* list; for ( int row = 0; row 5; row++ ) { list.append(new QStandardItem); } model.appendColumn(list); } TableView view; view.setModel(&model); view.show(); return a.exec();}#ifndef IVIEW_H#define IVIEW_Hclass IView {public: virtual void setMouseOver(const int) =0;};#endif // IVIEW_H #ifndef TABLEVIEW_H#define TABLEVIEW_H#include QTableView#include QMouseEvent#include QStandardItem #include IView.h#include Delegate.hclass TableView : public QTableView, public IView { Q_OBJECTprivate: int currHovered; void mouseMoveEvent(QMouseEvent *event); void disableMouseOver();public: TableView(QWidget *parent = 0); void setMouseOver(const int);};#endif // TABLEVIEW_H #include TableView.h#include QDebugTableView::TableView(QWidget *parent) : QTableView(parent), currHovered(-1){ Delegate *delegate = new Delegate; delegate-setView(this); setItemDelegate(delegate); setMouseTracking(true);} void TableView::setMouseOver(const int row){ if ( row == currHovered) return; QStandardItemModel *_model = static_castQStandardItemModel*(model()); for ( int col = 0; col _model-columnCount(); col++ ) { QStandardItem *item = _model-item(row, col); item-setBackground(QBrush(QColor(red))); } if ( currHovered != -1 ) { disableMouseOver(); } currHovered = row;} void TableView::disableMouseOver(){ QStandardItemModel *_model = static_castQStandardItemModel*(model()); for ( int col = 0; col _model-columnCount(); col++ ) { QStandardItem *item = _model-item(currHovered, col); item-setBackground(QBrush(QColor(white))); }} void TableView::mouseMoveEvent(QMouseEvent *event){ // TODO: you need know when mouse are not in table rect // then you need disable over QTableView::mouseMoveEvent(event);} #ifndef DELEGATE_H#define DELEGATE_H #include QStyledItemDelegate#include IView.hclass Delegate : public QStyledItemDelegate {private: IView *view;public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setView(IView *view) { this-view = view; }};#endif // DELEGATE_H #include Delegate.h#include QDebugvoid Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{ QStyleOptionViewItemV4 o = option; initStyleOption(&o, index); if ( o.state & QStyle::State_MouseOver ) { view-setMouseOver(index.row()); } o.state &= ~QStyle::State_MouseOver; QStyledItemDelegate::paint(painter, o, index);}
取消
评论