自定义ItemDelegate for QListView State_Selected

时间:2013-07-18 08:56:16

标签: qt qlistview qitemdelegate

我从QStyledItemDelegate创建了CustomItemDelegate,我正在使用paint()方法更好地了解我的QListView

如果我点击某个项目,option.state永远不会有State_Selected,为什么会这样? 我有一个选择模型,单个,行,选择矩形是可见的。

qDebug只打印出这些:

QStyle::State( "Active | Enabled" ) 
QStyle::State( "Active | Enabled | MouseOver" ) 

void SyrupItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{


   QRect rect = option.rect;
   qDebug() << option.state;

   if (option.state & QStyle::State_Selected)
   {


     painter->drawRoundedRect(option.rect,5,5);
     painter->setPen(QPen(QPalette::HighlightedText ) );

     if (option.state & QStyle::State_Active)
     {
        painter->setBrush(QBrush(QPalette().highlight()));
     } else
            {
                //painter->setBrush(QBrush(QPalette().color(QPalette::Inactive,
                //QPalette::Highlight)));
                QLinearGradient gradient(0, 0, 0, 100);
                gradient.setColorAt(0.0, QColor(0,0,230));
                gradient.setColorAt(1.0, QColor(250,250,250));
                painter->setBrush(gradient);
            }



   } else
        painter->setPen(QPen(QPalette::Text));

   if ( !index.isValid() )
   return;
    int row = index.row();

  //  painter->save();
   // painter->setRenderHint(QPainter::Antialiasing,true);


    QString res =   index.sibling(row,SyrupsSQLModel::SYRUP_NM_COL_INDEX).data().toString();

    QRectF rc(rect);

    rc.setTop(rc.top()+ PADDING);
    rc.setLeft(rc.left()+ 2* PADDING +  IMG_WIDTH);

    QFont font = option.font;
    font.setPointSize(font.pointSize()+4);
    painter->setFont(font);

    painter->drawText(rc,res);

    res = index.sibling(row,SyrupsSQLModel::SYRUP_GRP_COL_INDEX).data().toString().toLower();

    rc.setTop(rect.top()+PADDING );
    rc.setLeft(rect.left()+PADDING );
    painter->drawPixmap(rc.topLeft(),QIcon(":/prodgrp/"+res).pixmap(QSize(IMG_WIDTH,IMG_HEIGHT)));

    //SyrupsSQLModel::FORMULA_COL_INDEX:
    //SyrupsSQLModel::SYRUP_ID_COL_INDEX:
    //Painter->restore();

}

我正在使用Qt 5.0.2 32bit(Win)。

1 个答案:

答案 0 :(得分:0)

问题出在委托类中,我重新实现了editorEvent()函数。我评论出这些部分并且有效。