Example #1
0
void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
	const QAbstractItemModel *m = index.model();
	const QModelIndex idxc1 = index.sibling(index.row(), 1);
	QVariant data = m->data(idxc1);
	QList<QVariant> ql = data.toList();

	painter->save();

	QStyleOptionViewItemV4 o = option;
	initStyleOption(&o, index);

	QStyle *style = o.widget->style();
	QIcon::Mode iconMode = QIcon::Normal;

	QPalette::ColorRole colorRole = ((o.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::Text);
#if defined(Q_OS_WIN)
	// Qt's Vista Style has the wrong highlight color for treeview items
	// We can't check for QStyleSheetStyle so we have to search the children list search for a QWindowsVistaStyle
	QList<QObject *> hierarchy = style->findChildren<QObject *>();
	hierarchy.insert(0, style);
	foreach (QObject *obj, hierarchy) {
		if (QString::fromUtf8(obj->metaObject()->className()) == QString::fromUtf8("QWindowsVistaStyle")) {
			colorRole = QPalette::Text;
			break;
		}
	}
#endif

	// draw background
	style->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, o.widget);

	// resize rect to exclude the flag icons
	o.rect = option.rect.adjusted(0, 0, -FLAG_DIMENSION * ql.count(), 0);

	// draw icon
	QRect decorationRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &o, o.widget);
	o.icon.paint(painter, decorationRect, o.decorationAlignment, iconMode, QIcon::On);

	// draw text
	QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget);
	QString itemText = o.fontMetrics.elidedText(o.text, o.textElideMode, textRect.width());
	painter->setFont(o.font);
	style->drawItemText(painter, textRect, o.displayAlignment, o.palette, true, itemText, colorRole);

	// draw flag icons to original rect
	QRect ps = QRect(option.rect.right() - (ql.size() * FLAG_DIMENSION),
					 option.rect.y(), ql.size() * FLAG_DIMENSION,
					 option.rect.height());

	for (int i = 0; i < ql.size(); ++i) {
		QRect r = ps;
		r.setSize(QSize(FLAG_ICON_DIMENSION, FLAG_ICON_DIMENSION));
		r.translate(i * FLAG_DIMENSION + FLAG_ICON_PADDING, FLAG_ICON_PADDING);
		QRect p = QStyle::alignedRect(option.direction, option.decorationAlignment, r.size(), r);
		qvariant_cast<QIcon>(ql[i]).paint(painter, p, option.decorationAlignment, iconMode, QIcon::On);
	}

	painter->restore();
}
/*! Paints the week scale header.
 * \sa paintHeader()
 */
void DateTimeGrid::paintWeekScaleHeader( QPainter* painter,  const QRectF& headerRect, const QRectF& exposedRect,
                                        qreal offset, QWidget* widget )
{
    QStyle* style = widget?widget->style():QApplication::style();

    // Paint a section for each week
    QDateTime sdt = d->chartXtoDateTime( offset+exposedRect.left() );
    sdt.setTime( QTime( 0, 0, 0, 0 ) );
    // Go backwards until start of week
    while ( sdt.date().dayOfWeek() != d->weekStart ) sdt = sdt.addDays( -1 );
    QDateTime dt = sdt;
    for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
            dt = dt.addDays( 7 ),x=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()*7, headerRect.height()/2. ).toRect();
        opt.text = QString::number( dt.date().weekNumber() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }

    // Paint a section for each month
    dt = sdt;
    for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; x2=d->dateTimeToChartX( dt ) ) {
        //qDebug()<<"paintWeekScaleHeader()"<<dt;
        QDate next = dt.date().addMonths( 1 );
        next = next.addDays( 1 - next.day() );

        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*dt.date().daysTo( next ), headerRect.height()/2. ).toRect();
        opt.text = QDate::longMonthName( dt.date().month() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }

        dt.setDate( next );
    }
}
Example #3
0
void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem optionV4 = option;
    initStyleOption(&optionV4, index);

    QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();

    QTextDocument doc;
    doc.setHtml(optionV4.text);

    /// Painting item without text
    optionV4.text = QString();
    style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter);

    QAbstractTextDocumentLayout::PaintContext ctx;

    // Highlighting text if item is selected
    if (optionV4.state & QStyle::State_Selected)
        ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));

    QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
    painter->save();
    painter->translate(textRect.topLeft());
    painter->setClipRect(textRect.translated(-textRect.topLeft()));
    doc.documentLayout()->draw(painter, ctx);
    painter->restore();
}
Example #4
0
/*!
    Updates the \a editor for the item specified by \a index
    according to the style \a option given.
*/
void QStyledItemDelegate::updateEditorGeometry(QWidget *editor,
                                         const QStyleOptionViewItem &option,
                                         const QModelIndex &index) const
{
    if (!editor)
        return;
    Q_ASSERT(index.isValid());
    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);
    // let the editor take up all available space
    //if the editor is not a QLineEdit
    //or it is in a QTableView
#if QT_CONFIG(tableview) && QT_CONFIG(lineedit)
    if (qobject_cast<QExpandingLineEdit*>(editor) && !qobject_cast<const QTableView*>(widget))
        opt.showDecorationSelected = editor->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, 0, editor);
    else
#endif
        opt.showDecorationSelected = true;

    QStyle *style = widget ? widget->style() : QApplication::style();
    QRect geom = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);
    if ( editor->layoutDirection() == Qt::RightToLeft) {
        const int delta = qSmartMinSize(editor).width() - geom.width();
        if (delta > 0) {
            //we need to widen the geometry
            geom.adjust(-delta, 0, 0, 0);
        }
    }

    editor->setGeometry(geom);
}
Example #5
0
void ChatDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
   QStyleOptionViewItemV4 optionV4(option);
   this->initStyleOption(&optionV4, index);

   optionV4.state = option.state & (~QStyle::State_HasFocus);

   QStyle* style = optionV4.widget ? optionV4.widget->style() : QApplication::style();

   this->textDocument.setHtml(optionV4.text);
   this->textDocument.setTextWidth(optionV4.rect.width());

   optionV4.text = QString();
   style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter, optionV4.widget);

   QAbstractTextDocumentLayout::PaintContext ctx;
   ctx.palette = optionV4.palette;

   // Highlighting text if item is selected.
   if (optionV4.state & QStyle::State_Selected && optionV4.state & QStyle::State_Active)
       ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));

   QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
   painter->save();
   painter->translate(textRect.topLeft());
   painter->setClipRect(textRect.translated(-textRect.topLeft()));
   this->textDocument.documentLayout()->draw(painter, ctx);
   painter->restore();
}
void
SqlSearchDelegate::paint(QPainter *painter,
                      const QStyleOptionViewItem &option,
                      const QModelIndex &index) const
{
    QStyleOptionViewItemV4 optionV4 = option;
    initStyleOption(&optionV4, index);

    QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();

    QTextDocument doc;
    doc.setHtml(optionV4.text);
    optionV4.text = QString();
    style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter);

    QAbstractTextDocumentLayout::PaintContext ctx;
    QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled) ?
                (option.state & QStyle::State_Active) ? QPalette::Normal : QPalette::Inactive : QPalette::Disabled;

    if (optionV4.state & QStyle::State_Selected)
        ctx.palette.setColor(QPalette::Text, optionV4.palette.color(cg, QPalette::HighlightedText));
    else
        ctx.palette.setColor(QPalette::Text, optionV4.palette.color(cg, QPalette::WindowText));

    QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
    painter->save();
    painter->translate(textRect.topLeft());
    painter->setClipRect(textRect.translated(-textRect.topLeft()));
    doc.documentLayout()->draw(painter, ctx);
    painter->restore();
}
Example #7
0
void MessageViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 optionV4 = option;
    initStyleOption(&optionV4, index);

    QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();

    QTextDocument doc;
    QString align(index.data(MessageModel::TypeRole) == 1 ? "left" : "right");
    QString html = "<p align=\"" + align + "\" style=\"color:black;\">" + index.data(MessageModel::HTMLRole).toString() + "</p>";
    doc.setHtml(html);

    /// Painting item without text
    optionV4.text = QString();
    style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter);

    QAbstractTextDocumentLayout::PaintContext ctx;

    // Highlighting text if item is selected
    if (optionV4.state & QStyle::State_Selected)
        ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));

    QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
    doc.setTextWidth( textRect.width() );
    painter->save();
    painter->translate(textRect.topLeft());
    painter->setClipRect(textRect.translated(-textRect.topLeft()));
    doc.documentLayout()->draw(painter, ctx);
    painter->restore();
}
/*! Paints the day scale header.
 * \sa paintHeader()
 */
void DateTimeGrid::paintDayScaleHeader( QPainter* painter,  const QRectF& headerRect, const QRectF& exposedRect,
                                qreal offset, QWidget* widget )
{
    // For starters, support only the regular tab-per-day look
    QStyle* style = widget?widget->style():QApplication::style();

    // Paint a section for each day
    QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() );
    dt.setTime( QTime( 0, 0, 0, 0 ) );
    for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
          dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth(), headerRect.height()/2. ).toRect();
        opt.text = dt.toString( QString::fromAscii( "ddd" ) ).left( 1 );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }

    dt = d->chartXtoDateTime( offset+exposedRect.left() );
    dt.setTime( QTime( 0, 0, 0, 0 ) );
    // Go backwards until start of week
    while ( dt.date().dayOfWeek() != d->weekStart ) dt = dt.addDays( -1 );
    // Paint a section for each week
    for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset;
          dt = dt.addDays( 7 ),x2=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*7., headerRect.height()/2. ).toRect();
        opt.text = QString::number( dt.date().weekNumber() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }
}
void KOTodoRichTextDelegate::paint( QPainter *painter,
                                    const QStyleOptionViewItem &option,
                                    const QModelIndex &index ) const
{
  if ( index.data( KOTodoModel::IsRichTextRole ).toBool() ) {
    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, index );

    const QWidget *widget = opt.widget;
    QStyle *style = widget ? widget->style() : QApplication::style();

    QRect textRect = style->subElementRect( QStyle::SE_ItemViewItemText,
                                            &opt, widget );

    // draw the item without text
    opt.text.clear();
    style->drawControl( QStyle::CE_ItemViewItem, &opt, painter, widget );

    // draw the text (rich text)
    QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ?
                                QPalette::Normal : QPalette::Disabled;
    if ( cg == QPalette::Normal && !( opt.state & QStyle::State_Active ) ) {
      cg = QPalette::Inactive;
    }

    if ( opt.state & QStyle::State_Selected ) {
      painter->setPen(
        QPen( opt.palette.brush( cg, QPalette::HighlightedText ), 0 ) );
    } else {
      painter->setPen(
        QPen( opt.palette.brush( cg, QPalette::Text ), 0 ) );
    }
    if ( opt.state & QStyle::State_Editing ) {
      painter->setPen( QPen( opt.palette.brush( cg, QPalette::Text ), 0 ) );
      painter->drawRect( textRect.adjusted( 0, 0, -1, -1 ) );
    }

    m_textDoc->setHtml( index.data().toString() );

    painter->save();
    painter->translate( textRect.topLeft() );

    QRect tmpRect = textRect;
    tmpRect.moveTo( 0, 0 );
    m_textDoc->setTextWidth( tmpRect.width() );
    m_textDoc->drawContents( painter, tmpRect );

    painter->restore();
  } else {
    // align the text at top so that when it has more than two lines
    // it will just cut the extra lines out instead of aligning centered vertically
    QStyleOptionViewItem copy = option;
    copy.displayAlignment = Qt::AlignLeft | Qt::AlignTop;
    QStyledItemDelegate::paint( painter, copy, index );
  }
}
/*! Paints the hour scale header.
 * \sa paintHeader()
 */
void DateTimeGrid::paintHourScaleHeader( QPainter* painter,  const QRectF& headerRect, const QRectF& exposedRect,
                                qreal offset, QWidget* widget )
{
    QStyle* style = widget?widget->style():QApplication::style();

    // Paint a section for each hour
    QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() );
    dt.setTime( QTime( dt.time().hour(), 0, 0, 0 ) );
    for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
          dt = dt.addSecs( 60*60 /*1 hour*/ ),x=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()/24., headerRect.height()/2. ).toRect();
        opt.text = dt.time().toString( QString::fromAscii( "hh" ) );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }

    dt = d->chartXtoDateTime( offset+exposedRect.left() );
    dt.setTime( QTime( 0, 0, 0, 0 ) );
    // Paint a section for each day
    for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset;
          dt = dt.addDays( 1 ),x2=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth(), headerRect.height()/2. ).toRect();
        opt.text = QDate::longDayName( dt.date().dayOfWeek() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }
}
Example #11
0
void ProcessItemDelegate::paint(QPainter * painter,
  const QStyleOptionViewItem &option, const QModelIndex & index) const
{
  QStyleOptionViewItemV4 opt = option;
  initStyleOption(&opt, index);

  painter->save();
  painter->setClipRect(opt.rect);

  // Draw the background.
  const QWidget * widget = opt.widget;
  QStyle * style = widget ? widget->style() : QApplication::style();
  style->proxy()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, widget);

  QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt,
    widget);
  QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);

  // Draw the icon.
  QIcon::Mode mode = QIcon::Normal;
  if (!(opt.state & QStyle::State_Enabled))
  {
    mode = QIcon::Disabled;
  }
  else if (opt.state & QStyle::State_Selected)
  {
    mode = QIcon::Selected;
  }
  QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off;
  opt.icon.paint(painter, iconRect, opt.decorationAlignment, mode, state);

  // Draw the text.
  QTextDocument doc;
  doc.setHtml(opt.text);
  doc.setDocumentMargin(2);
  painter->translate(textRect.topLeft());
  doc.drawContents(painter);

  painter->restore();
}
Example #12
0
/*!
  \reimp
*/
bool QStyledItemDelegate::editorEvent(QEvent *event,
                                QAbstractItemModel *model,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index)
{
    Q_ASSERT(event);
    Q_ASSERT(model);

    // make sure that the item is checkable
    Qt::ItemFlags flags = model->flags(index);
    if (!(flags & Qt::ItemIsUserCheckable) || !(option.state & QStyle::State_Enabled)
        || !(flags & Qt::ItemIsEnabled))
        return false;

    // make sure that we have a check state
    QVariant value = index.data(Qt::CheckStateRole);
    if (!value.isValid())
        return false;

    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
    QStyle *style = widget ? widget->style() : QApplication::style();

    // make sure that we have the right event type
    if ((event->type() == QEvent::MouseButtonRelease)
        || (event->type() == QEvent::MouseButtonDblClick)
        || (event->type() == QEvent::MouseButtonPress)) {
        QStyleOptionViewItem viewOpt(option);
        initStyleOption(&viewOpt, index);
        QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, widget);
        QMouseEvent *me = static_cast<QMouseEvent*>(event);
        if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
            return false;

        if ((event->type() == QEvent::MouseButtonPress)
            || (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;
    }

    Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
    if (flags & Qt::ItemIsUserTristate)
        state = ((Qt::CheckState)((state + 1) % 3));
    else
        state = (state == Qt::Checked) ? Qt::Unchecked : Qt::Checked;
    return model->setData(index, state, Qt::CheckStateRole);
}
Example #13
0
void RazorPanelPluginPrivate::paintEvent(QPaintEvent* event)
{
    Q_Q(RazorPanelPlugin);

    if (mMovable)
    {
        QPainter p(q);
        QStyle *style = q->style();
        QStyleOptionToolBar opt;
        initStyleOption(&opt);

        opt.rect = style->subElementRect(QStyle::SE_ToolBarHandle, &opt, q);
        if (opt.rect.isValid())
            style->drawPrimitive(QStyle::PE_IndicatorToolBarHandle, &opt, &p, q);
    }
}
Example #14
0
void BlinkingDecorationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter,option,index);
    QVariant var = index.data(Qt::DecorationRole);
    QColor color = var.value<QColor>();
    if((color.red()==255)&&(!m_red))
    {
       QStyleOptionViewItemV4 opt = option;
       QStyledItemDelegate::initStyleOption(&opt, index);
       QStyle* style = opt.widget ? opt.widget->style() : QApplication::style();

       QRect rect = style->subElementRect( QStyle::SE_ItemViewItemDecoration ,&opt);

       painter->fillRect(rect,QColor(Qt::darkGreen));

    }
}
void ProgressBarDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option,
 const QModelIndex &index ) const
{
    QStyle *style;

    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, index );

    style = opt.widget ? opt.widget->style() : QApplication::style();
    style->drawPrimitive( QStyle::PE_PanelItemViewItem, &opt, painter );

    if ( !( opt.state & QStyle::State_Editing ) ) {
        bool ok = false;
        (void) index.data().toInt(&ok);
        if ( ok ) {
            QStyleOptionProgressBar pbOption;
            pbOption.QStyleOption::operator=( option );
            initStyleOptionProgressBar( &pbOption, index );

            style->drawControl( QStyle::CE_ProgressBar, &pbOption, painter );
            // Draw focus, copied from qt
            if (opt.state & QStyle::State_HasFocus) {
                painter->save();
                QStyleOptionFocusRect o;
                o.QStyleOption::operator=( opt );
                o.rect = style->subElementRect( QStyle::SE_ItemViewItemFocusRect, &opt, opt.widget );
                o.state |= QStyle::State_KeyboardFocusChange;
                o.state |= QStyle::State_Item;
                QPalette::ColorGroup cg = ( opt.state & QStyle::State_Enabled )
                                ? QPalette::Normal : QPalette::Disabled;
                o.backgroundColor = opt.palette.color( cg, ( opt.state & QStyle::State_Selected )
                                                ? QPalette::Highlight : QPalette::Window );
                style->drawPrimitive( QStyle::PE_FrameFocusRect, &o, painter, opt.widget );
                //kDebug(planDbg())<<"Focus"<<o.rect<<opt.rect<<pbOption.rect;
                painter->restore();
            }
        } else {
            EnumDelegate del;
            del.paint( painter, option, index );
        }
    }
}
bool CheckStateItemDelegate::editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index )
{
    Q_ASSERT(event);
    Q_ASSERT(model);
    kDebug(planDbg());

    Qt::ItemFlags flags = model->flags(index);
    if ( ! ( option.state & QStyle::State_Enabled ) || ! ( flags & Qt::ItemIsEnabled ) ) {
        return false;
    }

    // make sure that we have a check state
    QVariant value = index.data( Qt::EditRole );
    if ( ! value.isValid() ) {
        return false;
    }

    QStyle *style = QApplication::style();

    // make sure that we have the right event type
    if ( ( event->type() == QEvent::MouseButtonRelease ) || ( event->type() == QEvent::MouseButtonDblClick ) || ( event->type() == QEvent::MouseButtonPress ) ) {
        QStyleOptionViewItemV4 viewOpt( option );
        initStyleOption( &viewOpt, index );
        QRect checkRect = style->subElementRect( QStyle::SE_ItemViewItemDecoration, &viewOpt, 0 );
        QMouseEvent *me = static_cast<QMouseEvent*>( event );
        if ( me->button() != Qt::LeftButton || ! checkRect.contains( me->pos() ) ) {
            return false;
        }
        if ( ( event->type() == QEvent::MouseButtonPress ) || ( 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;
    }
    Qt::CheckState state = ( static_cast<Qt::CheckState>( value.toInt() ) == Qt::Checked ? Qt::Unchecked : Qt::Checked );
    return model->setData(index, state, Qt::CheckStateRole);
}
/*! \reimp */
void QToolBar::paintEvent(QPaintEvent *)
{
    Q_D(QToolBar);

    QPainter p(this);
    QStyle *style = this->style();
    QStyleOptionToolBar opt;
    initStyleOption(&opt);

    if (d->layout->expanded || d->layout->animating || isWindow()) {
        //if the toolbar is expended, we need to fill the background with the window color
        //because some styles may expects that.
        p.fillRect(opt.rect, palette().background());
        style->drawControl(QStyle::CE_ToolBar, &opt, &p, this);
        style->drawPrimitive(QStyle::PE_FrameMenu, &opt, &p, this);
    } else {
        style->drawControl(QStyle::CE_ToolBar, &opt, &p, this);
    }

    opt.rect = style->subElementRect(QStyle::SE_ToolBarHandle, &opt, this);
    if (opt.rect.isValid())
        style->drawPrimitive(QStyle::PE_IndicatorToolBarHandle, &opt, &p, this);
}
Example #18
0
	void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
		painter->save();
		QStyle *style = option.widget->style();
		style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, option.widget);

		QRect contentsRect = style->subElementRect(QStyle::SE_ItemViewItemText,
												   &option,
												   option.widget);
		int a = contentsRect.height();

		/* Draw DecorationRole */
		QRect DecorationRect(contentsRect.topLeft(), option.decorationSize);
		DecorationRect.translate( (a-option.decorationSize.width())/2, (a-option.decorationSize.height())/2);
		painter->drawPixmap(DecorationRect, index.data(Qt::DecorationRole).value<QIcon>().pixmap(option.decorationSize));

		/* Draw DisplayRole */
		QRect DisplayRect(contentsRect.adjusted(a+3,0,0,0));
		QString text = QFontMetrics(option.font).elidedText(
					index.data(Qt::DisplayRole).toString(),
					option.textElideMode,
					DisplayRect.width());
		painter->drawText(DisplayRect, Qt::AlignVCenter|Qt::AlignLeft, text);
		painter->restore();
	}
Example #19
0
void RenderThemeQStyle::computeSizeBasedOnStyle(RenderStyle* renderStyle) const
{
    QSize size(0, 0);
    const QFontMetrics fm(renderStyle->font().font());
    QStyle* style = qStyle();

    switch (renderStyle->appearance()) {
    case TextAreaPart:
    case SearchFieldPart:
    case TextFieldPart: {
        int padding = findFrameLineWidth(style);
        renderStyle->setPaddingLeft(Length(padding, Fixed));
        renderStyle->setPaddingRight(Length(padding, Fixed));
        renderStyle->setPaddingTop(Length(padding, Fixed));
        renderStyle->setPaddingBottom(Length(padding, Fixed));
        break;
    }
    default:
        break;
    }
    // If the width and height are both specified, then we have nothing to do.
    if (!renderStyle->width().isIntrinsicOrAuto() && !renderStyle->height().isAuto())
        return;

    switch (renderStyle->appearance()) {
    case CheckboxPart: {
        QStyleOption styleOption;
        styleOption.state |= QStyle::State_Small;
        int checkBoxWidth = style->pixelMetric(QStyle::PM_IndicatorWidth, &styleOption);
        checkBoxWidth *= renderStyle->effectiveZoom();
        size = QSize(checkBoxWidth, checkBoxWidth);
        break;
    }
    case RadioPart: {
        QStyleOption styleOption;
        styleOption.state |= QStyle::State_Small;
        int radioWidth = style->pixelMetric(QStyle::PM_ExclusiveIndicatorWidth, &styleOption);
        radioWidth *= renderStyle->effectiveZoom();
        size = QSize(radioWidth, radioWidth);
        break;
    }
    case PushButtonPart:
    case ButtonPart: {
        QStyleOptionButton styleOption;
        styleOption.state |= QStyle::State_Small;
        QSize contentSize = fm.size(Qt::TextShowMnemonic, QString::fromLatin1("X"));
        QSize pushButtonSize = style->sizeFromContents(QStyle::CT_PushButton,
                                                       &styleOption, contentSize, 0);
        styleOption.rect = QRect(0, 0, pushButtonSize.width(), pushButtonSize.height());
        QRect layoutRect = style->subElementRect(QStyle::SE_PushButtonLayoutItem,
                                                 &styleOption, 0);

        // If the style supports layout rects we use that, and  compensate accordingly
        // in paintButton() below.
        if (!layoutRect.isNull())
            size.setHeight(layoutRect.height());
        else
            size.setHeight(pushButtonSize.height());

        break;
    }
    case MenulistPart: {
        QStyleOptionComboBox styleOption;
        styleOption.state |= QStyle::State_Small;
        int contentHeight = qMax(fm.lineSpacing(), 14) + 2;
        QSize menuListSize = style->sizeFromContents(QStyle::CT_ComboBox,
                                                     &styleOption, QSize(0, contentHeight), 0);
        size.setHeight(menuListSize.height());
        break;
    }
    default:
        break;
    }

    // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
    if (renderStyle->width().isIntrinsicOrAuto() && size.width() > 0)
        renderStyle->setMinWidth(Length(size.width(), Fixed));
    if (renderStyle->height().isAuto() && size.height() > 0)
        renderStyle->setMinHeight(Length(size.height(), Fixed));
}
Example #20
0
void SearchItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                               const QModelIndex &index) const
{
    QStyleOptionViewItem opt(option);

    QStyle *style = opt.widget->style();

    // Find decoration roles with data present.
    QList<int> roles;
    for (int role : m_decorationRoles) {
        if (!index.data(role).isNull())
            roles.append(role);
    }

    /// TODO: Implemented via initStyleOption() overload
    if (!roles.isEmpty()) {
        opt.features |= QStyleOptionViewItem::HasDecoration;
        opt.icon = index.data(roles.first()).value<QIcon>();

        const QSize actualSize = opt.icon.actualSize(opt.decorationSize);
        opt.decorationSize = {std::min(opt.decorationSize.width(), actualSize.width()),
                              std::min(opt.decorationSize.height(), actualSize.height())};
    }

    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);

    const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt, opt.widget) + 1;

    if (!roles.isEmpty()) {
        QIcon::Mode mode = QIcon::Normal;
        if (!(opt.state & QStyle::State_Enabled))
            mode = QIcon::Disabled;
        else if (opt.state & QStyle::State_Selected)
            mode = QIcon::Selected;
        const QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off;

        // All icons are sized after the first one.
        QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, opt.widget);
        const int dx = iconRect.width() + margin;

        for (int i = 1; i < roles.size(); ++i) {
            opt.decorationSize.rwidth() += dx;
            iconRect.translate(dx, 0);

            const QIcon icon = index.data(roles[i]).value<QIcon>();
            icon.paint(painter, iconRect, opt.decorationAlignment, mode, state);
        }
    }

    // Match QCommonStyle behaviour.
    const QString text = index.data().toString();
    const QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget)
            .adjusted(margin, 0, -margin, 0);

    const QFontMetrics &fm = opt.fontMetrics;
    const QString elidedText = fm.elidedText(text, opt.textElideMode, textRect.width());

    if (!m_highlight.isEmpty()) {
        painter->save();
        painter->setRenderHint(QPainter::Antialiasing);
        painter->setPen(QColor::fromRgb(255, 253, 0));

        const QColor highlightColor = opt.state & (QStyle::State_Selected | QStyle::State_HasFocus)
                ? QColor::fromRgb(255, 255, 100, 20) : QColor::fromRgb(255, 255, 100, 120);

        for (int i = 0;;) {
            const int matchIndex = text.indexOf(m_highlight, i, Qt::CaseInsensitive);
            if (matchIndex == -1 || matchIndex >= elidedText.length() - 1)
                break;

            QRect highlightRect
                    = textRect.adjusted(fm.width(elidedText.left(matchIndex)), 2, 0, -2);
            highlightRect.setWidth(fm.width(elidedText.mid(matchIndex, m_highlight.length())));

            QPainterPath path;
            path.addRoundedRect(highlightRect, 2, 2);

            painter->fillPath(path, highlightColor);
            painter->drawPath(path);

            i = matchIndex + m_highlight.length();
        }

        painter->restore();
    }

    painter->save();

#ifdef Q_OS_WIN32
    // QWindowsVistaStyle overrides highlight colour.
    if (style->objectName() == QStringLiteral("windowsvista")) {
        opt.palette.setColor(QPalette::All, QPalette::HighlightedText,
                             opt.palette.color(QPalette::Active, QPalette::Text));
    }
#endif

    const QPalette::ColorGroup cg = opt.state & QStyle::State_Active
            ? QPalette::Normal : QPalette::Inactive;

    if (opt.state & QStyle::State_Selected)
        painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
    else
        painter->setPen(opt.palette.color(cg, QPalette::Text));

    // Vertically align the text in the middle to match QCommonStyle behaviour.
    const QRect alignedRect = QStyle::alignedRect(opt.direction, opt.displayAlignment,
                                                  QSize(1, fm.height()), textRect);
    painter->drawText(QPoint(alignedRect.x(), alignedRect.y() + fm.ascent()), elidedText);
    painter->restore();
}
Example #21
0
void RichTextDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);

    if (!opt.text.contains(QLatin1Char('<'))) {
        QStyledItemDelegate::paint(painter, option, index);
        return;
    }

    QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();

    QString text = opt.text;
    opt.text.clear();
    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);

    QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget);

    QString key = QLatin1String("RichTextDelegate-") + text;
    QPixmap pm;
    if (!QPixmapCache::find(key, &pm)) {
        m_doc->setDefaultFont(opt.font);

        QTextOption textOpt = m_doc->defaultTextOption();
        textOpt.setAlignment(QStyle::visualAlignment(opt.direction, opt.displayAlignment));
        bool wrapText = opt.features & QStyleOptionViewItemV2::WrapText;
        textOpt.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap);
        textOpt.setTextDirection(opt.direction);
        m_doc->setDefaultTextOption(textOpt);

        QTextFrameFormat fmt = m_doc->rootFrame()->frameFormat();
        fmt.setMargin(0);
        m_doc->rootFrame()->setFrameFormat(fmt);

        m_doc->setTextWidth(textRect.width());
        m_doc->setHtml(text);

        QAbstractTextDocumentLayout::PaintContext context;
        context.palette = opt.palette;
        context.palette.setColor(QPalette::Text, context.palette.light().color());

        pm = QPixmap(m_doc->size().width(), m_doc->size().height());
        pm.fill(Qt::transparent);
        QPainter pmPainter(&pm);
        m_doc->documentLayout()->draw(&pmPainter, context);

        QPixmapCache::insert(key, pm);
    }

    int hDelta = textRect.width() - pm.width();
    int vDelta = textRect.height() - pm.height();
    int x = textRect.left();
    int y = textRect.top();

    if (opt.displayAlignment & Qt::AlignVCenter)
        y += vDelta / 2;
    else if (opt.displayAlignment & Qt::AlignBottom)
        y += vDelta;

    if (opt.displayAlignment & Qt::AlignHCenter)
        x += hDelta / 2;
    else if (opt.displayAlignment & Qt::AlignRight)
        x += hDelta;

    painter->drawPixmap(x, y, pm);
}
/** Redefined. */
void PlaylistItemDelegate::paint(QPainter *p, const QStyleOptionViewItem &opt, const QModelIndex &index) const
{
	QStyleOptionViewItem o(opt);
	initStyleOption(&o, index);

	QStyle *style = QApplication::style();
	QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget);

	if (_playlist->horizontalHeader()->visualIndex(index.column()) == 0) {
		textRect = textRect.adjusted(1, 0, 0, 0);
		o.rect = textRect;
	}

	MiamStyledItemDelegate::paint(p, o, index);

	// Highlight the current playing item
	QFont font = SettingsPrivate::instance()->font(SettingsPrivate::FF_Playlist);
	if (_playlist->mediaPlaylist()->currentIndex() == index.row() && _playlist->mediaPlayer()->state() != QMediaPlayer::StoppedState) {
		font.setBold(true);
		font.setItalic(true);
	}
	p->setFont(font);

	p->save();
	if (o.state.testFlag(QStyle::State_Selected)) {
		if ((opt.palette.highlight().color().lighter(160).saturation() - opt.palette.highlightedText().color().saturation()) < 128) {
			p->setPen(opt.palette.text().color());
		} else {
			p->setPen(opt.palette.highlightedText().color());
		}
	}

	QString text;
	switch (index.column()) {

	case Playlist::COL_LENGTH:
		if (index.data().toInt() >= 0) {
			text = QDateTime::fromTime_t(index.data().toInt()).toString("m:ss");
			text = p->fontMetrics().elidedText(text, o.textElideMode, textRect.width());
			style->drawItemText(p, textRect, Qt::AlignCenter, o.palette, true, text);
		}
		break;
	case Playlist::COL_TRACK_NUMBER:
	case Playlist::COL_YEAR:
		text = p->fontMetrics().elidedText(index.data().toString(), o.textElideMode, textRect.width());
		style->drawItemText(p, textRect, Qt::AlignCenter, o.palette, true, text);
		break;
	case Playlist::COL_RATINGS:
		if (index.data().canConvert<StarRating>() || opt.state.testFlag(QStyle::State_Selected)) {
			StarRating r = index.data().value<StarRating>();
			r.paintStars(p, opt);
		}
		break;
	case Playlist::COL_ICON:{
		//QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &o, o.widget);
		text = p->fontMetrics().elidedText(index.data().toString(), o.textElideMode, textRect.width());
		QSize iconSize(textRect.height() * 0.8, textRect.height() * 0.8);
		/// FIXME
		//style->drawItemText(p, textRect, Qt::AlignCenter, o.palette, true, text);
		style->drawItemPixmap(p, o.rect, Qt::AlignCenter, o.icon.pixmap(iconSize));
		break;
	}
	case Playlist::COL_TITLE:
	case Playlist::COL_ALBUM:
	case Playlist::COL_ARTIST:
	default:
		text = p->fontMetrics().elidedText(index.data().toString(), o.textElideMode, textRect.width());
		if (QApplication::isLeftToRight()) {
			textRect.adjust(2, 0, 0, 0);
		} else {
			textRect.adjust(0, 0, -2, 0);
		}
		style->drawItemText(p, textRect, Qt::AlignLeft | Qt::AlignVCenter, o.palette, true, text);
		break;
	}
	p->restore();
}
Example #23
0
void ChangesDelegate::paint(QPainter *painter,
                        const QStyleOptionViewItem &option,
                        const QModelIndex &index) const
{
    if (!index.isValid()) {
        return;
    }
    bool leftToRight = (painter->layoutDirection() == Qt::LeftToRight);

    QStyleOptionViewItemV4 opt(option);
    QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
    painter->save();
    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);
    painter->restore();

    //grab the package from the index pointer
    QString pkgName       = index.data(PackageModel::NameRole).toString();
    QString pkgSummary    = index.data(PackageModel::SummaryRole).toString();
    QString pkgVersion    = index.data(PackageModel::VersionRole).toString();
    QString pkgArch       = index.data(PackageModel::ArchRole).toString();
//     QString pkgIconPath   = index.data(PackageModel::IconPathRole).toString();
    bool    pkgChecked    = index.data(PackageModel::CheckStateRole).toBool();
    bool    pkgCheckable  = !index.data(Qt::CheckStateRole).isNull();
    Transaction::Info info;
    info = index.data(PackageModel::InfoRole).value<Transaction::Info>();
    bool    pkgInstalled  = (info == Transaction::InfoInstalled ||
                             info == Transaction::InfoCollectionInstalled);

    bool    pkgCollection = (info == Transaction::InfoCollectionInstalled ||
                             info == Transaction::InfoCollectionAvailable);

    QIcon emblemIcon;
    if (pkgCheckable) {
        // update kind icon
        emblemIcon = index.data(PackageModel::IconRole).value<QIcon>();
    } else {
        emblemIcon = m_checkedIcon;
    }

    // pain the background (checkbox and the extender)
    if (m_extendPixmapWidth) {
        KExtendableItemDelegate::paint(painter, opt, index);
    }

    int leftCount;
    if (leftToRight) {
        opt.rect.setLeft(option.rect.left() + m_extendPixmapWidth + UNIVERSAL_PADDING);
        leftCount = opt.rect.left() + UNIVERSAL_PADDING;
    } else {
        opt.rect.setRight(option.rect.right() - m_extendPixmapWidth - UNIVERSAL_PADDING);
        leftCount = opt.rect.width() - (UNIVERSAL_PADDING + MAIN_ICON_SIZE);
    }

    int left = opt.rect.left();
    int top = opt.rect.top();
    int width = opt.rect.width();

    QStyleOptionButton optBt;
    optBt.rect = opt.rect;
    if (pkgCheckable) {
        optBt.rect = style->subElementRect(QStyle::SE_CheckBoxIndicator, &optBt);
        // Count the checkbox size
        if (leftToRight) {
            leftCount += optBt.rect.width();
        } else {
            leftCount -= optBt.rect.width();
        }
    } else  if ((option.state & QStyle::State_MouseOver) ||
                (option.state & QStyle::State_Selected) ||
                !pkgChecked) {
        if (leftToRight) {
            optBt.rect.setLeft(left + width - (m_buttonSize.width() + UNIVERSAL_PADDING));
            width -= m_buttonSize.width() + UNIVERSAL_PADDING;
        } else {
            optBt.rect.setLeft(left + UNIVERSAL_PADDING);
            left += m_buttonSize.width() + UNIVERSAL_PADDING;
        }
        // Calculate the top of the button which is the item height - the button height size divided by 2
        // this give us a little value which is the top and bottom margin
        optBt.rect.setTop(optBt.rect.top() + ((calcItemHeight(option) - m_buttonSize.height()) / 2));
        optBt.rect.setSize(m_buttonSize); // the width and height sizes of the button
        optBt.features = QStyleOptionButton::Flat;
        optBt.iconSize = m_buttonIconSize;
        optBt.icon = pkgInstalled ? m_removeIcon   : m_installIcon;
        optBt.text = pkgInstalled ? m_removeString : m_installString;
        if (pkgChecked) {
            optBt.state |= QStyle::State_Raised | QStyle::State_Active | QStyle::State_Enabled;;
        } else {
            if ((option.state & QStyle::State_MouseOver) &&
                !(option.state & QStyle::State_Selected)) {
                optBt.state |= QStyle::State_MouseOver;
            }
            optBt.state |= QStyle::State_Sunken | QStyle::State_Active | QStyle::State_Enabled;
        }
        style->drawControl(QStyle::CE_PushButton, &optBt, painter);
    }

// QAbstractItemView *view = qobject_cast<QAbstractItemView*>(parent());
//             QPoint pos = view->viewport()->mapFromGlobal(QCursor::pos());
//     kDebug() << pos;


    // selects the mode to paint the icon based on the info field
    QIcon::Mode iconMode = QIcon::Normal;
    if (option.state & QStyle::State_MouseOver) {
        iconMode = QIcon::Active;
    }

    QColor foregroundColor = (option.state.testFlag(QStyle::State_Selected))?
    option.palette.color(QPalette::HighlightedText):option.palette.color(QPalette::Text);

    // Painting main column
    QStyleOptionViewItem local_option_title(option);
    QStyleOptionViewItem local_option_normal(option);

    local_option_normal.font.setPointSize(local_option_normal.font.pointSize() - 1);

    QPixmap pixmap(option.rect.size());
    pixmap.fill(Qt::transparent);
    QPainter p(&pixmap);
    p.translate(-option.rect.topLeft());

    // Main icon
    QIcon icon;
    if (pkgCollection) {
        icon = m_collectionIcon;
    } else {
        icon = PkIcons::getIcon(index.data(PackageModel::IconRole).toString(), QString());
        if (icon.isNull()) {
            icon = m_packageIcon;
        }
    }
//     if (pkgIconPath.isEmpty()) {
//        icon = pkgCollection ? m_collectionIcon : m_packageIcon;
//     } else {
//         icon = PkIcons::getIcon(pkgIconPath, "package");
//     }

    int iconSize = calcItemHeight(option) - 2 * UNIVERSAL_PADDING;
    icon.paint(&p,
               leftCount,
               top + UNIVERSAL_PADDING,
               iconSize,
               iconSize,
               Qt::AlignCenter,
               iconMode);

    int textWidth;
    if (leftToRight) {
        // add the main icon
        leftCount += iconSize + UNIVERSAL_PADDING;
        textWidth = width - (leftCount - left);
    } else {
        leftCount -= UNIVERSAL_PADDING;
        textWidth = leftCount - left;
        leftCount = left;
    }


    // Painting

    // Text
    const int itemHeight = calcItemHeight(option);

    p.setPen(foregroundColor);
    // compose the top line
    // Collections does not have version and arch
    if (option.state & QStyle::State_MouseOver && !pkgCollection) {
        //! pkgName = pkgName + " - " + pkgVersion + (pkgArch.isNull() ? NULL : " (" + pkgArch + ')');
    }

    // draw the top line
    int topTextHeight = QFontInfo(local_option_title.font).pixelSize();
    p.setFont(local_option_title.font);
    p.drawText(leftCount,
               top,
               textWidth,
               topTextHeight + UNIVERSAL_PADDING,
               Qt::AlignVCenter | Qt::AlignLeft,
               pkgName);

    // draw the bottom line
    iconSize = topTextHeight + UNIVERSAL_PADDING;
    if (pkgCheckable || pkgInstalled) {
        emblemIcon.paint(&p,
                         leftToRight ? leftCount : (textWidth + left) - iconSize,
                         top + topTextHeight + UNIVERSAL_PADDING,
                         iconSize,
                         iconSize,
                         Qt::AlignVCenter | Qt::AlignHCenter,
                         iconMode);
    }

    // store the original opacity
    qreal opa = p.opacity();
    if (!(option.state & QStyle::State_MouseOver) && !(option.state & QStyle::State_Selected)) {
        p.setOpacity(opa / 2.5);
    }

    p.setFont(local_option_normal.font);
    p.drawText(leftToRight ? leftCount + iconSize + UNIVERSAL_PADDING : left - UNIVERSAL_PADDING,
               top + itemHeight / 2,
               textWidth - iconSize,
               QFontInfo(local_option_normal.font).pixelSize() + UNIVERSAL_PADDING,
               Qt::AlignTop | Qt::AlignLeft,
               pkgSummary);
    p.setOpacity(opa);

    QLinearGradient gradient;
    // Gradient part of the background - fading of the text at the end
    if (leftToRight) {
        gradient = QLinearGradient(left + width - UNIVERSAL_PADDING - FADE_LENGTH,
                                   0,
                                   left + width - UNIVERSAL_PADDING,
                                   0);
        gradient.setColorAt(0, Qt::white);
        gradient.setColorAt(1, Qt::transparent);
    } else {
        gradient = QLinearGradient(left + UNIVERSAL_PADDING,
                                   0,
                                   left + UNIVERSAL_PADDING + FADE_LENGTH,
                                   0);
        gradient.setColorAt(0, Qt::transparent);
        gradient.setColorAt(1, Qt::white);
    }

    QRect paintRect = option.rect;
    p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
    p.fillRect(paintRect, gradient);

    if (leftToRight) {
        gradient.setStart(left + width
                - (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE) - FADE_LENGTH, 0);
        gradient.setFinalStop(left + width
                - (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE), 0);
    } else {
        gradient.setStart(left + UNIVERSAL_PADDING
                + (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE), 0);
        gradient.setFinalStop(left + UNIVERSAL_PADDING
                + (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE) + FADE_LENGTH, 0);
    }
    paintRect.setHeight(UNIVERSAL_PADDING + MAIN_ICON_SIZE / 2);
    p.fillRect(paintRect, gradient);
    p.setCompositionMode(QPainter::CompositionMode_SourceOver);
    p.end();

    painter->drawPixmap(option.rect.topLeft(), pixmap);
}
Example #24
0
NS_IMETHODIMP
nsNativeThemeQt::GetMinimumWidgetSize(nsRenderingContext* aContext, nsIFrame* aFrame,
                                      PRUint8 aWidgetType,
                                      nsIntSize* aResult, bool* aIsOverridable)
{
    (*aResult).width = (*aResult).height = 0;
    *aIsOverridable = PR_TRUE;

    QStyle *s = qApp->style();

    PRInt32 p2a = aContext->AppUnitsPerDevPixel();

    switch (aWidgetType) {
    case NS_THEME_RADIO:
    case NS_THEME_CHECKBOX: {
        nsRect frameRect = aFrame->GetRect();

        QRect qRect = qRectInPixels(frameRect, p2a);

        QStyleOptionButton option;

        InitButtonStyle(aWidgetType, aFrame, qRect, option);

        QRect rect = s->subElementRect(
                         (aWidgetType == NS_THEME_CHECKBOX) ?
                         QStyle::SE_CheckBoxIndicator :
                         QStyle::SE_RadioButtonIndicator,
                         &option,
                         NULL);

        (*aResult).width = rect.width();
        (*aResult).height = rect.height();
        break;
    }
    case NS_THEME_BUTTON: {
        nsRect frameRect = aFrame->GetRect();

        QRect qRect = qRectInPixels(frameRect, p2a);

        QStyleOptionButton option;

        InitButtonStyle(aWidgetType, aFrame, qRect, option);

        QRect rect = s->subElementRect(
                         QStyle::SE_PushButtonFocusRect,
                         &option,
                         NULL);

        (*aResult).width = rect.width();
        (*aResult).height = rect.height();
        break;
    }
    case NS_THEME_SCROLLBAR_BUTTON_UP:
    case NS_THEME_SCROLLBAR_BUTTON_DOWN: {
        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarExtent);
        (*aResult).height = (*aResult).width;
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_SCROLLBAR_BUTTON_LEFT:
    case NS_THEME_SCROLLBAR_BUTTON_RIGHT: {
        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarExtent);
        (*aResult).width = (*aResult).height;
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_SCROLLBAR_THUMB_VERTICAL: {
        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarExtent);
        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarSliderMin);
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_SCROLLBAR_THUMB_HORIZONTAL: {
        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarSliderMin);
        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarExtent);
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_SCROLLBAR_TRACK_VERTICAL: {
        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarExtent);
        (*aResult).height = s->pixelMetric(QStyle::PM_SliderLength);
        break;
    }
    case NS_THEME_SCROLLBAR_TRACK_HORIZONTAL: {
        (*aResult).width = s->pixelMetric(QStyle::PM_SliderLength);
        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarExtent);
        break;
    }
    case NS_THEME_DROPDOWN_BUTTON: {
        QStyleOptionComboBox comboOpt;

        nsRect frameRect = aFrame->GetRect();
        QRect qRect = qRectInPixels(frameRect, p2a);
        comboOpt.rect = qRect;

        InitComboStyle(aWidgetType, aFrame, qRect, comboOpt);

        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, &comboOpt, QStyle::SC_ComboBoxArrow, NULL);

        (*aResult).width = subRect.width();
        (*aResult).height = subRect.height();
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_DROPDOWN: {
        QStyleOptionComboBox comboOpt;

        nsRect frameRect = aFrame->GetRect();
        QRect qRect = qRectInPixels(frameRect, p2a);
        comboOpt.rect = qRect;

        InitComboStyle(aWidgetType, aFrame, qRect, comboOpt);

        QRect subRect = s->subControlRect(QStyle::CC_ComboBox,
                                          &comboOpt,
                                          QStyle::SC_ComboBoxFrame,
                                          NULL);

        (*aResult).width = subRect.width();
        (*aResult).height = subRect.height();
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_DROPDOWN_TEXT: {
        QStyleOptionComboBox comboOpt;

        nsRect frameRect = aFrame->GetRect();

        QRect qRect = qRectInPixels(frameRect, p2a);

        comboOpt.rect = qRect;

        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, &comboOpt, QStyle::SC_ComboBoxEditField, NULL);

        (*aResult).width = subRect.width();
        (*aResult).height = subRect.height();
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_DROPDOWN_TEXTFIELD: {
        QStyleOptionComboBox comboOpt;

        nsRect frameRect = aFrame->GetRect();

        QRect qRect = qRectInPixels(frameRect, p2a);

        comboOpt.rect = qRect;

        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, &comboOpt, QStyle::SC_ComboBoxArrow, NULL);
        QRect subRect2 = s->subControlRect(QStyle::CC_ComboBox, &comboOpt, QStyle::SC_ComboBoxFrame, NULL);

        (*aResult).width = subRect.width() + subRect2.width();
        (*aResult).height = std::max(subRect.height(), subRect2.height());
        //*aIsOverridable = PR_FALSE;
        break;
    }
    case NS_THEME_TEXTFIELD:
    case NS_THEME_TEXTFIELD_MULTILINE:
        break;
    }
    return NS_OK;
}
Example #25
0
nsresult
nsNativeThemeQt::DrawWidgetBackground(QPainter *qPainter,
                                      nsRenderingContext* aContext,
                                      nsIFrame* aFrame,
                                      PRUint8 aWidgetType,
                                      const nsRect& aRect,
                                      const nsRect& aClipRect)

{
    gfxContext* context = aContext->ThebesContext();
    nsRefPtr<gfxASurface> surface = context->CurrentSurface();

    context->UpdateSurfaceClip();

    QStyle* style = qApp->style();

    qPainter->save();

    gfxPoint offs = surface->GetDeviceOffset();
    qPainter->translate(offs.x, offs.y);

    gfxMatrix ctm = context->CurrentMatrix();
    if (!ctm.HasNonTranslation()) {
        ctm.x0 = NSToCoordRound(ctm.x0);
        ctm.y0 = NSToCoordRound(ctm.y0);
    }

    QMatrix qctm(ctm.xx, ctm.yx, ctm.xy, ctm.yy, ctm.x0, ctm.y0);
    qPainter->setWorldMatrix(qctm, true);

    PRInt32 p2a = aContext->AppUnitsPerDevPixel();

    QRect r = qRectInPixels(aRect, p2a);
    QRect cr = qRectInPixels(aClipRect, p2a);

    QStyle::State extraFlags = QStyle::State_None;

    switch (aWidgetType) {
    case NS_THEME_RADIO:
    case NS_THEME_CHECKBOX: {
        QStyleOptionButton opt;
        InitButtonStyle (aWidgetType, aFrame, r, opt);

        if (aWidgetType == NS_THEME_CHECKBOX)
        {
            style->drawPrimitive (QStyle::PE_IndicatorCheckBox, &opt, qPainter);
        } else {
            style->drawPrimitive (QStyle::PE_IndicatorRadioButton, &opt, qPainter);
        }
        break;
    }
    case NS_THEME_BUTTON:
    case NS_THEME_BUTTON_BEVEL: {
        QStyleOptionButton opt;
        InitButtonStyle (aWidgetType, aFrame, r, opt);

        if (aWidgetType == NS_THEME_BUTTON) {
            style->drawPrimitive(QStyle::PE_PanelButtonCommand, &opt, qPainter);
            if (IsDefaultButton(aFrame))
                style->drawPrimitive(QStyle::PE_FrameDefaultButton, &opt, qPainter);
        } else {
            style->drawPrimitive(QStyle::PE_PanelButtonBevel, &opt, qPainter);
            style->drawPrimitive(QStyle::PE_FrameButtonBevel, &opt, qPainter);
        }
        break;
    }
    case NS_THEME_SCROLLBAR: {
        qPainter->fillRect(r, qApp->palette().brush(QPalette::Normal, QPalette::Window));
        break;
    }
    case NS_THEME_SCROLLBAR_TRACK_HORIZONTAL: {
        qPainter->fillRect(r, qApp->palette().brush(QPalette::Active, QPalette::Window));
        break;
    }
    case NS_THEME_SCROLLBAR_TRACK_VERTICAL: {
        qPainter->fillRect(r, qApp->palette().brush(QPalette::Active, QPalette::Window));
        break;
    }
    case NS_THEME_SCROLLBAR_BUTTON_LEFT: {
        QStyleOptionSlider opt;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt, QStyle::State_Horizontal);
        opt.orientation = Qt::Horizontal;
        style->drawControl(QStyle::CE_ScrollBarSubLine, &opt, qPainter, NULL);
        break;
    }
    case NS_THEME_SCROLLBAR_BUTTON_RIGHT: {
        QStyleOptionSlider opt;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt, QStyle::State_Horizontal);
        opt.orientation = Qt::Horizontal;
        style->drawControl(QStyle::CE_ScrollBarAddLine, &opt, qPainter, NULL);
        break;
    }
    case NS_THEME_SCROLLBAR_BUTTON_UP: {
        QStyleOptionSlider opt;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt);
        opt.orientation = Qt::Vertical;
        style->drawControl(QStyle::CE_ScrollBarSubLine, &opt, qPainter, NULL);
        break;
    }
    case NS_THEME_SCROLLBAR_BUTTON_DOWN: {
        QStyleOptionSlider opt;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt);
        opt.orientation = Qt::Vertical;
        style->drawControl(QStyle::CE_ScrollBarAddLine, &opt, qPainter, NULL);
        break;
    }
    case NS_THEME_SCROLLBAR_THUMB_HORIZONTAL: {
        extraFlags |= QStyle::State_Horizontal;
        QStyleOptionSlider option;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)option, extraFlags);
        option.orientation = Qt::Horizontal;
        style->drawControl(QStyle::CE_ScrollBarSlider, &option, qPainter, NULL);
        break;
    }
    case NS_THEME_SCROLLBAR_THUMB_VERTICAL: {
        QStyleOptionSlider option;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)option, extraFlags);
        option.orientation = Qt::Vertical;
        style->drawControl(QStyle::CE_ScrollBarSlider, &option, qPainter, NULL);
        break;
    }
    case NS_THEME_DROPDOWN: {
        QStyleOptionComboBox comboOpt;

        InitComboStyle(aWidgetType, aFrame, r, comboOpt);

        style->drawComplexControl(QStyle::CC_ComboBox, &comboOpt, qPainter);
        break;
    }
    case NS_THEME_DROPDOWN_BUTTON: {
        QStyleOptionComboBox option;

        InitComboStyle(aWidgetType, aFrame, r, option);

        style->drawPrimitive(QStyle::PE_FrameDefaultButton, &option, qPainter);
        style->drawPrimitive(QStyle::PE_IndicatorSpinDown, &option, qPainter);
        break;
    }
    case NS_THEME_DROPDOWN_TEXT:
    case NS_THEME_DROPDOWN_TEXTFIELD:
    case NS_THEME_TEXTFIELD:
    case NS_THEME_TEXTFIELD_MULTILINE:
    case NS_THEME_LISTBOX: {
        QStyleOptionFrameV2 frameOpt;
        nsEventStates eventState = GetContentState(aFrame, aWidgetType);

        if (!IsDisabled(aFrame, eventState))
            frameOpt.state |= QStyle::State_Enabled;

        frameOpt.rect = r;
        frameOpt.features = QStyleOptionFrameV2::Flat;

        if (aWidgetType == NS_THEME_TEXTFIELD || aWidgetType == NS_THEME_TEXTFIELD_MULTILINE) {
            QRect contentRect = style->subElementRect(QStyle::SE_LineEditContents, &frameOpt);
            contentRect.adjust(mFrameWidth, mFrameWidth, -mFrameWidth, -mFrameWidth);
            qPainter->fillRect(contentRect, QBrush(Qt::white));
        }

        frameOpt.palette = mNoBackgroundPalette;
        style->drawPrimitive(QStyle::PE_FrameLineEdit, &frameOpt, qPainter, NULL);
        break;
    }
    case NS_THEME_MENUPOPUP: {
        QStyleOptionMenuItem option;
        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)option, extraFlags);
        style->drawPrimitive(QStyle::PE_FrameMenu, &option, qPainter, NULL);
        break;
    }
    default:
        break;
    }

    qPainter->restore();
    return NS_OK;
}
Example #26
0
	void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
	{
		//	QStyledItemDelegate::paint(painter, option, index);
		painter->save();
		QStyle *style = option.widget->style();
		style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, option.widget);

	/*
	 *  a = rect.height
	 * fm(x) := fontmetrics of x
	 * DR := DisplayRole
	 * UR := UserRole
	 *             a                            rect.width-a
	 *  +---------------------+------------------------------------------------+
	 *  |                     |                                                |
	 *  |   +-------------+   |                                                |
	 *  |   |             |   |                                                |
	 *  |   |             |   |a*fm(DR)/(fm(DR)+fm(UR))            DisplayRole |
	 * a|   |     icon    |   |                                                |
	 *  |   |             |   |                                                |
	 *  |   |             |   +------------------------------------------------+
	 *  |   |             |   |                                                |
	 *  |   +-------------+   |a*fm(UR)/(fm(DR)+fm(UR))             UserRole+x |
	 *  |                     |                                                |
	 * +-----------------------------------------------------------------------+
	 */

		QRect contentsRect = style->subElementRect(QStyle::SE_ItemViewItemText,
												   &option,
												   option.widget);
		int a = contentsRect.height();

		/* Draw icon */
		QRect iconRect(contentsRect.topLeft(), option.decorationSize);
		iconRect.translate( (a-option.decorationSize.width())/2, (a-option.decorationSize.height())/2);
		painter->drawPixmap(iconRect, index.data(Qt::DecorationRole).value<QIcon>().pixmap(option.decorationSize));

		/* Draw name */
		QRect DRTextRect(contentsRect.adjusted(
							 a,0,
							 0,-a*12/(option.fontMetrics.height()+12)) // TODO
						 );
		DRTextRect.adjust(3,-2,0,-2);  // Empirical
		QFont font = option.font;
		QString text = QFontMetrics(font).elidedText(
					index.data(Qt::DisplayRole).toString(),
					option.textElideMode,
					DRTextRect.width());
		painter->setFont(font);
		painter->drawText(DRTextRect, Qt::AlignVCenter|Qt::AlignLeft, text);

		/* Draw the infotext */
		QRect URTextRect(contentsRect.adjusted(
							 a,DRTextRect.height(),
							 0,0)
						 );
		URTextRect.adjust(3,-4,0,-4);  // Empirical
		font.setPixelSize(12);
		text = QFontMetrics(font).elidedText(
					index.data(_subtextRole).toString(),
					option.textElideMode,
					URTextRect.width());
		painter->setFont(font);
		painter->drawText(URTextRect, Qt::AlignVCenter|Qt::AlignLeft, text);

		painter->restore();
	}
Example #27
0
// Based on QCommonStyle::drawControl case CE_ItemViewItem
void FilesDelegate::paint( QPainter *p, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
// 	QStyledItemDelegate::paint(p, option, index);
// 	return;

	Q_ASSERT(index.isValid());

	QStyleOptionViewItemV4 opt = option;
	initStyleOption(&opt, index);
	const QWidget *widget = opt.widget;
	const QTreeView *view = qobject_cast<const QTreeView *>(widget);
        QStyle *style = widget ? widget->style() : qApp->style();
// 	style->drawControl(QStyle::CE_ItemViewItem, &opt, p, widget);
// 	return;

#if defined(Q_OS_WIN32)
	// Based on QWindowsVistaStyle::drawControl case CE_ItemViewItem
	if (FilesDelegate_win_useVista(style))
	{
		QPalette palette = opt.palette;
		palette.setColor(QPalette::All, QPalette::HighlightedText, palette.color(QPalette::Active, QPalette::Text));
		// Note that setting a saturated color here results in ugly XOR colors in the focus rect
		palette.setColor(QPalette::All, QPalette::Highlight, palette.base().color().darker(108));

		opt.palette = palette;
		// We hide the focusrect in singleselection as it is not required
		if ((view->selectionMode() == QAbstractItemView::SingleSelection) && !(opt.state & QStyle::State_KeyboardFocusChange))
			opt.state &= ~QStyle::State_HasFocus;
	}
#endif

	// Custom padding for first and last columns; Also fixing viewItemPosition for swapped columns
	if (!view->header()->logicalIndex(index.column()))
	{
		opt.rect.setLeft(opt.rect.left() + VIEWPORT_MARGIN_LEFT);
		opt.viewItemPosition = QStyleOptionViewItemV4::Beginning;
	}
	if (view->header()->logicalIndex(index.column()) == index.model()->columnCount() - 1)
	{
		opt.rect.setRight(opt.rect.right() - VIEWPORT_MARGIN_RIGHT);
		opt.viewItemPosition = QStyleOptionViewItemV4::End;
	}


	p->save();
	p->setClipRect(opt.rect);

	QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &opt, widget);
	QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, widget);
	QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);

	// Initially selected elements have State_Selected state, but it's not what we want, so we remove it and set background color
	if (opt.state & QStyle::State_Selected)
	{
		opt.state &= ~(QStyle::State_Selected);
		opt.backgroundBrush = QBrush(QColor(255, 215, 188)); // Soft orange-pink color for selection
	}

	// State_Selected state is used for displaying cursor row only
	if (currentRow == index.data(FileListModel::IndexRowRole).toInt())
		opt.state |= QStyle::State_Selected;

	// draw the background
	style->proxy()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, p, widget);

	// draw the check mark
	if (opt.features & QStyleOptionViewItemV2::HasCheckIndicator)
	{
		QStyleOptionViewItemV4 option(opt);
		option.rect = checkRect;
		option.state = option.state & ~QStyle::State_HasFocus;

		switch (opt.checkState)
		{
		case Qt::Unchecked:
			option.state |= QStyle::State_Off;
			break;
		case Qt::PartiallyChecked:
			option.state |= QStyle::State_NoChange;
			break;
		case Qt::Checked:
			option.state |= QStyle::State_On;
			break;
		}
		style->proxy()->drawPrimitive(QStyle::PE_IndicatorViewItemCheck, &option, p, widget);
	}

	// draw the icon
	QIcon::Mode mode = QIcon::Normal;
	if (!(opt.state & QStyle::State_Enabled))
		mode = QIcon::Disabled;
	else if (opt.state & QStyle::State_Selected)
		mode = QIcon::Selected;
	QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off;
	opt.icon.paint(p, iconRect, opt.decorationAlignment, mode, state);

	// draw the text
	if (!opt.text.isEmpty())
	{
		QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;
		if (cg == QPalette::Normal && !(opt.state & QStyle::State_Active))
			cg = QPalette::Inactive;

		if (opt.state & QStyle::State_Selected)
			p->setPen(opt.palette.color(cg, QPalette::HighlightedText));
		else
			p->setPen(opt.palette.color(cg, QPalette::Text));

		if (opt.state & QStyle::State_Editing)
		{
			p->setPen(opt.palette.color(cg, QPalette::Text));
			p->drawRect(textRect.adjusted(0, 0, -1, -1));
		}

		QCommonStylePrivate_viewItemDrawText(style, p, &opt, textRect, !(index.data(FileListModel::AttributesRole).toUInt() & FileInfo::Directory));
	}

	// draw the focus rect
// 	if (opt.state & QStyle::State_HasFocus)
// 	{
// 		QStyleOptionFocusRect o;
// 		o.QStyleOption::operator=(opt);
// 		o.rect = style->subElementRect(QStyle::SE_ItemViewItemFocusRect, &opt, widget);
// 		o.state |= QStyle::State_KeyboardFocusChange;
// 		o.state |= QStyle::State_Item;
// 		QPalette::ColorGroup cg = (opt.state & QStyle::State_Enabled)	? QPalette::Normal : QPalette::Disabled;
// 		o.backgroundColor = opt.palette.color(cg, (opt.state & QStyle::State_Selected) ? QPalette::Highlight : QPalette::Window);
// 		style->proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, p, widget);
// 	}

	p->restore();
}
Example #28
0
static void computeSizeBasedOnStyle(RenderStyle* renderStyle)
{
    // If the width and height are both specified, then we have nothing to do.
    if (!renderStyle->width().isIntrinsicOrAuto() && !renderStyle->height().isAuto())
        return;

    QSize size(0, 0);
    const QFontMetrics fm(renderStyle->font().font());
    QStyle* applicationStyle = QApplication::style();

    switch (renderStyle->appearance()) {
    case CheckboxAppearance: {
        QStyleOption styleOption;
        styleOption.state |= QStyle::State_Small;
        int checkBoxWidth = applicationStyle->pixelMetric(QStyle::PM_IndicatorWidth,
                                                          &styleOption);
        size = QSize(checkBoxWidth, checkBoxWidth);
        break;
    }
    case RadioAppearance: {
        QStyleOption styleOption;
        styleOption.state |= QStyle::State_Small;
        int radioWidth = applicationStyle->pixelMetric(QStyle::PM_ExclusiveIndicatorWidth,
                                                       &styleOption);
        size = QSize(radioWidth, radioWidth);
        break;
    }
    case PushButtonAppearance:
    case ButtonAppearance: {
        QStyleOptionButton styleOption;
        styleOption.state |= QStyle::State_Small;
        QSize contentSize = fm.size(Qt::TextShowMnemonic, QString::fromLatin1("X"));
        QSize pushButtonSize = applicationStyle->sizeFromContents(QStyle::CT_PushButton,
                                                                  &styleOption,
                                                                  contentSize,
                                                                  0);
        styleOption.rect = QRect(0, 0, pushButtonSize.width(), pushButtonSize.height());
        QRect layoutRect = applicationStyle->subElementRect(QStyle::SE_PushButtonLayoutItem,
                                                                  &styleOption,
                                                                  0);
        // If the style supports layout rects we use that, and
        // compensate accordingly in paintButton() below.
        if (!layoutRect.isNull()) {
            size.setHeight(layoutRect.height());
        } else {
            size.setHeight(pushButtonSize.height());
        }

        break;
    }
    case MenulistAppearance: {
        QStyleOptionComboBox styleOption;
        styleOption.state |= QStyle::State_Small;
        int contentHeight = qMax(fm.lineSpacing(), 14) + 2;
        QSize menuListSize = applicationStyle->sizeFromContents(QStyle::CT_ComboBox,
                                                        &styleOption,
                                                        QSize(0, contentHeight),
                                                        0);
        size.setHeight(menuListSize.height());
        break;
    }
    case TextFieldAppearance: {
        const int verticalMargin = 1;
        const int horizontalMargin = 2;
        int h = qMax(fm.lineSpacing(), 14) + 2*verticalMargin;
        int w = fm.width(QLatin1Char('x')) * 17 + 2*horizontalMargin;
        QStyleOptionFrameV2 opt;
        opt.lineWidth = applicationStyle->pixelMetric(QStyle::PM_DefaultFrameWidth,
                                                           &opt, 0);
        QSize sz = applicationStyle->sizeFromContents(QStyle::CT_LineEdit,
                                                           &opt,
                                                           QSize(w, h).expandedTo(QApplication::globalStrut()),
                                                           0);
        size.setHeight(sz.height());
        break;
    }
    default:
        break;
    }

    // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
    if (renderStyle->width().isIntrinsicOrAuto() && size.width() > 0)
        renderStyle->setWidth(Length(size.width(), Fixed));
    if (renderStyle->height().isAuto() && size.height() > 0)
        renderStyle->setHeight(Length(size.height(), Fixed));
}