2011-03-29 116 views
7
自繪的每一行「按鈕」

我想畫「可點擊」圖標(或按鈕),在我用我自己的自定義「QAbstractItemDelegate」一而QListView的每一行派生類油漆。這些按鈕可能隨着行的自定義狀態而改變(我可以在繪畫過程中訪問底層的數據結構)。的Qt:可點擊與QAbstractItemDelegate

解決這個問題的最好方法是什麼?

回答

6

免責聲明:這可能不是最好的方式,但在這裏你有完全控制權的方式。我們發現有必要使用繪圖複選框來執行此操作。

您可以繼承QStyledItemDelegate(或QAbstractItemDelegate可能工作..還沒有嘗試過)並重新實現了painteditorEvent方法。您可以使用QStyle::drawControl()(設置適當的樣式選項後)繪製控制paint,然後手動測試在editorEvent鼠標命中並用它做什麼。如果內存正確地爲我服務,則此代碼很大程度上受到啓發(咳嗽,複製,咳嗽,咳嗽)從查看QStyledItemDelegate的Qt源代碼。

void CheckBoxDelegate::paint(QPainter *painter, 
          const QStyleOptionViewItem &option, 
          const QModelIndex &index) const { 
    bool checked = index.model()->data(index, Qt::DisplayRole).toBool(); 

    if (option.state & QStyle::State_Selected) { 
    painter->setPen(QPen(Qt::NoPen)); 
    if (option.state & QStyle::State_Active) { 
     painter->setBrush(QBrush(QPalette().highlight())); 
    } 
    else { 
     painter->setBrush(QBrush(QPalette().color(QPalette::Inactive, 
               QPalette::Highlight))); 
    } 
    painter->drawRect(option.rect); 
    } 

QStyleOptionButton check_box_style_option; 
    check_box_style_option.state |= QStyle::State_Enabled; 
    if (checked) { 
    check_box_style_option.state |= QStyle::State_On; 
    } else { 
    check_box_style_option.state |= QStyle::State_Off; 
    } 
    check_box_style_option.rect = CheckBoxRect(option); 

    QApplication::style()->drawControl(QStyle::CE_CheckBox, 
            &check_box_style_option, 
            painter); 
} 

bool CheckBoxDelegate::editorEvent(QEvent *event, 
            QAbstractItemModel *model, 
            const QStyleOptionViewItem &option, 
            const QModelIndex &index) { 
    if ((event->type() == QEvent::MouseButtonRelease) || 
     (event->type() == QEvent::MouseButtonDblClick)) { 
    QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event); 
    if (mouse_event->button() != Qt::LeftButton || 
     !CheckBoxRect(option).contains(mouse_event->pos())) { 
     return true; 
    } 
    if (event->type() == QEvent::MouseButtonDblClick) { 
     return true; 
    } 
    } else if (event->type() == QEvent::KeyPress) { 
    if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space && 
     static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select) { 
     return false; 
    } 
    } else { 
    return false; 
    } 

    bool checked = model->data(index, Qt::DisplayRole).toBool(); 
    return model->setData(index, !checked, Qt::EditRole); 
} 
+0

感謝。會試一試。 – JasonGenX 2011-03-29 20:47:55

+1

有一個問題,我如何檢測鼠標在給定行的區域上移動「進入」和「離開」? (如果我想要實現的鼠標光標下的當前行的高亮) – JasonGenX 2011-03-30 14:18:34

+0

我認爲這是'的QEvent :: MouseMove',但我不能完全肯定。大概最容易做的事情是把一個'qDebug()<< event->型()'語句在那裏,趕你的應用程序,然後通過雜草不管它吐出來找到你需要處理的事件。 – 2011-03-30 14:46:18