1. 程式人生 > >Qt 筆記:深入解析檢視與委託

Qt 筆記:深入解析檢視與委託

檢視與委託

-檢視負責確定資料項的組織顯示方式(列表,樹形,表格)

-委託負責具體資料項的顯示和編輯(資料值,編輯器)

-檢視和委託共同完成資料顯示功能和資料編輯功能

自定義委託的預設資料顯示方式

-重寫paint成員函式

-在paint中自定義資料顯示方式

-重寫editorEvent成員函式

-在editorEvent中處理互動事件

在paint中自定義資料顯示方式

if(index.data().type() == QVariant::Bool)
{
    bool data = index.model()->data(index,Qt::DispalyRole).toBool();
    QStyleOptionButton checkBoxStyle;    //元件繪製引數
    
    /* 設定具體的繪製引數 */
    checkBoxStyle.state = data? QStyle::State_On : QStyle::State_Off;
    checkBoxStyle.state |= QStyle::State_Enabled;
    checkBoxStyle.rect = option.rect;
    checkBoxStyle.rect.setX(option.rect.x() + option.rect.width() / 2 -6);

    /* 根據引數繪製元件(資料項自定義顯示方式)*/
    QApplication::style()->drawControl(QStyle::CE_CheckBox,&checkBoxStyle,painter);
}

在editorEvent中處理互動事件

if(index.data().type() == QVariant::Bool)
{
    QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);

    if(event->type() == QEvent::MouseButtonPress &&
        option.rect.contains(mouseEvent->pos()))
    {
        bool data = model->data(index,Qt::DisplayRole).toBool();
        model->setData(index, !data,Qt::DisplayRole);
    }

}

委託是檢視的重要構成部分

-檢視負責資料項的組織顯示方式

-委託負責具體資料項中的數值的顯示方式

-重寫委託的paint函式自定義資料項顯示方式

-重寫委託的editorEvent函式處理互動事件