Qt--委託

原文

Delegate  類

概念 MVC模式不同,model/view結構沒有用於與用戶交互的完全獨立的組件。一般來講, view負責把數據展示給用戶,也處理用戶的輸入。爲了獲得更多的靈性性,交互通過delegagte執行。它既提供輸入功能又負責渲染view中的每個數據項。 
使用Delegate的原因  Qt中當用到QTreeView和QTableView等用於顯示item的視圖時,你要編輯一個item用到的編輯工具可能是除了默認文字編輯lineEdit以外的工具,例如button,spinBox,甚至Slider,ProgressBar,也有可能是自定義的widget。所以Qt提供了一個委託類,用來處理View中的數據展示方式。

Delegate類的繼承架構見下圖,

        自從Qt4.4,出現了兩個delegate基類,QStyledItemDelegate vs. QItemDelegate。默認的delegate是QStyledItemDelegate,即你不自己寫delegate的時候,默認那個lineEdit是來自QStyledItemDelegate。Qt Assistant建議用戶如果自定義delegate或者用到了Qt style sheets的話,最好繼承自QStyledItemDelegate,爲什麼呢?首先這兩個類在繪製代理和爲item提供編輯器上面是獨立的,沒什麼聯繫,互不影響;不同的是QStyledItemDelegate使用當前style來繪製item(的代理),即如果程序設置了總體的風格(用QSS或其他定義方式),QStyledItemDelegate會使用這個風格設置。

先看看Qt Demos看了裏面spinboxDelegat的例子:
1. 自定義的delegate繼承自QItemDelegate。

2. 必須重載的一些函數:
       (1)  QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const;
       (2)  void setEditorData(QWidget *editor, const QModelIndex &index) const;
       (3)  void setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const;
       (4)  void updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &index) const;

3. createEditor創建自定義widget並返回之。
        setEditorData是將model中當前有的數據設置到代理上。自己從model取出數據,自己setValue到editor上。
        setModelData是將editor上的數據保存到Model中。
        updateEditorGeometry就是將editor設置到一定位置,並且有一定大小,使這個editor看起來像是正好嵌入到格子裏面一樣。用的是option.rect。

4. closeEditor() signal 表明用戶完成編輯數據,編輯控件可以銷燬。

5. commitData() signal 必須在完成編輯數據之後,發送該信號,將會把新數據寫回Model

6. paint() and sizeHint(), QitemDelegate默認繼承了該方法,如果需要特殊風格繪製單元項中內容,還需重載這兩個函數。

下面有三個例子可以簡單的說明Qt中如何使用委託

 

例子1: SpinBoxDelegate,繼承於QItemDelegate

 

例子2:trackeditor,繼承於QItemDelegate

 

例子3: 繼承於 QStyledItemDelegate

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章