在QListView中添加radiobutton
在QListView中添加radiobutton,用到了model/view結構,那么首先我們先對他有個了解。Model-View-Controller(MVC),是從Smalltalk發展而來的一種設計模式,常被用于構建用戶界面。經典設計模式的著作中有這樣的描述:
MVC 由三種對象組成。Model是應用中的的程序對象,View是它的屏幕表示,Controller定義了用戶界面如何對用戶輸入進行響應。在MVC之前,用戶界面設計傾向于三者揉合在一起,MVC對它們進行了解耦,提高了靈活性與重用性。
假如把view與controller結合在一起,結果就是model/view結構。這個結構依然是把數據存儲與數據表示進行了分離,它與MVC都基于同樣的思想,但它更簡單一些。這種分離使得在幾個不同的view上顯示同一個數據成為可能,也可以重新實現新的view,而不必改變底層的數據結構。為了更靈活的對用戶輸入進行處理,引入了delegate這個概念。它的好處是,數據項的渲染與編程可以進行定制。
其實這個MVC模式,model進行數據的訪問與處理,view提供顯示,而delegate則負責進行item的render,Qt中在使用的時候,如下
1、 Create a existing model
QDirModel *model = new QDirModel;
2 、Create the list view
QListView *list = new QListView(…);
3、 Display the item
list->setModel(model);
4 、Create a existing model
QDirModel *model = new QDirModel;
5、 Create the list view
QListView *list = new QListView(…);
6、 Display the item
list->setModel(model);
至于與delegate的關聯,我們可以用list->setItemDelegate(new QItemDelegate());
在QListView中,如果我們要使用一個check box,我們可以直接在model類中data函數處理
- QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
- {
- if(role == Qt::CheckStateRole)
- {
- return true;
- }
- .......
- }
這樣在QListView中就可以顯示出勾選的check box,但是如果需要進行radio button的顯示,我們還需要進行一些相關處理。
在QItemDelegate中,有一個drawCheck函數
- virtual void drawCheck ( QPainter * painter, const QStyleOptionViewItem & option, const QRect & rect, Qt::CheckState state ) const
- {
- if (!rect.isValid())
- return;
- QStyleOptionViewItem opt(option);
- opt.rect = rect;
- optopt.state = opt.state & ~QStyle.:State_HasFocus;
- switch (state) {
- case Qt::Unchecked:
- opt.state |= QStyle.:State_Off;
- break;
- case Qt::PartiallyChecked:
- opt.state |= QStyle.:State_NoChange;
- break;
- case Qt::Checked:
- opt.state |= QStyle.:State_On;
- break;
- }
- QApplication::style()->drawPrimitive(QStyle.:PE_IndicatorViewItemCheck, &opt, painter);
- }
該函數實現了check box的繪制,對于qt來說,check box與radio button在某些方面來說是一樣的,只是在各自的樣式上面的有點不一樣,也就是對于style的繪制不一樣,于是參考qt中QStyle類,使用QStyle.:PE_IndeicatorRadioButton進行重新繪制,就可以變成radio button樣式
QApplication::style()->drawPrimitive(QStyle.:PE_IndicatorRadioButton, &opt, painter);
于是我們重寫一個drawRadio函數,與drawCheck一樣,就是***一句使用上面處理。
然后我們重寫delegate相關paint函數,
- void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
- {
- QRect checkSpace; //the rect for draw check
- int isCheck = index.model()->data(index, Qt::CheckStateRole).toInt(); //get the index item's check state
- if(isCheck)
- drawRadio(painter, option, checkSpace, Qt::Checked);
- else
- drawRadio(painter, option, checkSpace, Qt::Unchecked);
- ... ... //draw others like display role, decroration role
- }
小結:關于在QListView中添加radiobutton的內容就介紹到這里,Model-View-Controller(MVC),是從Smalltalk發展而來的一種設計模式,常被用于構建用戶界面。想必你因該了解了MVC結構了吧!
【編輯推薦】