void LedgerDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); // never change the background of the cell the mouse is hovering over opt.state &= ~QStyle::State_MouseOver; // show the focus only on the detail column opt.state &= ~QStyle::State_HasFocus; if(index.column() == LedgerModel::DetailColumn) { QAbstractItemView* view = qobject_cast< QAbstractItemView* >(parent()); if(view) { if(view->currentIndex().row() == index.row()) { opt.state |= QStyle::State_HasFocus; } } } painter->save(); // Background QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); // Do not paint text if the edit widget is shown const LedgerView *view = qobject_cast<const LedgerView *>(opt.widget); if (view && view->indexWidget(index)) { painter->restore(); return; } const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1; const QRect textArea = QRect(opt.rect.x() + margin, opt.rect.y() + margin, opt.rect.width() - 2 * margin, opt.rect.height() - 2 * margin); QStringList lines; if(index.column() == LedgerModel::DetailColumn) { lines << index.model()->data(index, LedgerModel::PayeeNameRole).toString(); lines << index.model()->data(index, LedgerModel::CounterAccountRole).toString(); lines << index.model()->data(index, LedgerModel::SingleLineMemoRole).toString(); lines.removeAll(QString()); } const bool erroneous = index.model()->data(index, LedgerModel::ErroneousRole).toBool(); const bool selected = opt.state & QStyle::State_Selected; // draw the text items if(!opt.text.isEmpty() || !lines.isEmpty()) { // check if it is a scheduled transaction and display it as inactive if(!index.model()->data(index, LedgerModel::ScheduleIdRole).toString().isEmpty()) { opt.state &= ~QStyle::State_Enabled; } 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(opt.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(opt.palette.color(cg, QPalette::Text)); } if (opt.state & QStyle::State_Editing) { painter->setPen(opt.palette.color(cg, QPalette::Text)); painter->drawRect(textArea.adjusted(0, 0, -1, -1)); } // Don't play with the color if it's selected // otherwise switch the color if the transaction has errors if(erroneous && !selected) { painter->setPen(m_erroneousColor); } // collect data for the various colums if(index.column() == LedgerModel::DetailColumn) { for(int i = 0; i < lines.count(); ++i) { painter->drawText(textArea.adjusted(0, (opt.fontMetrics.lineSpacing() + 5) * i, 0, 0), opt.displayAlignment, lines[i]); } } else { painter->drawText(textArea, opt.displayAlignment, opt.text); } } // draw the focus rect if(opt.state & QStyle::State_HasFocus) { QStyleOptionFocusRect o; o.QStyleOption::operator=(opt); o.rect = style->proxy()->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->proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, opt.widget); } if((index.column() == LedgerModel::DetailColumn) && erroneous) { QPixmap attention; attention.loadFromData(attentionSign, sizeof(attentionSign), 0, 0); style->proxy()->drawItemPixmap(painter, option.rect, Qt::AlignRight | Qt::AlignTop, attention); } painter->restore(); #if 0 const QHeaderView* horizontalHeader = view->horizontalHeader(); const QHeaderView* verticalHeader = view->verticalHeader(); const QWidget* viewport = view->viewport(); const bool showGrid = view->showGrid() && !view->indexWidget(index); const int gridSize = showGrid ? 1 : 0; const int gridHint = style->styleHint(QStyle::SH_Table_GridLineColor, &option, view); const QColor gridColor = static_cast<QRgb>(gridHint); const QPen gridPen = QPen(gridColor, 0, view->gridStyle()); const bool rightToLeft = view->isRightToLeft(); const int viewportOffset = horizontalHeader->offset(); // QStyledItemDelegate::paint(painter, opt, index); if(!horizontalHeader->isSectionHidden(LedgerModel::DateColumn)) { QDate postDate = index.data(LedgerModel::PostDateRole).toDate(); if(postDate.isValid()) { int ofs = horizontalHeader->sectionViewportPosition(LedgerModel::DateColumn) + viewportOffset; QRect oRect = opt.rect; opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop; opt.rect.setLeft(opt.rect.left()+ofs); opt.rect.setTop(opt.rect.top()+margin); opt.rect.setWidth(horizontalHeader->sectionSize(LedgerModel::DateColumn)); opt.text = KGlobal::locale()->formatDate(postDate, QLocale::ShortFormat); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); opt.rect = oRect; } } if(!horizontalHeader->isSectionHidden(LedgerModel::DetailColumn)) { QString payee = index.data(LedgerModel::PayeeRole).toString(); QString counterAccount = index.data(LedgerModel::CounterAccountRole).toString(); QString txt = payee; if(payee.length() > 0) txt += '\n'; txt += counterAccount; int ofs = horizontalHeader->sectionViewportPosition(LedgerModel::DetailColumn) + viewportOffset; QRect oRect = opt.rect; opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop; opt.rect.setLeft(opt.rect.left()+ofs); opt.rect.setTop(opt.rect.top()+margin); opt.rect.setWidth(horizontalHeader->sectionSize(LedgerModel::DetailColumn)); opt.text = txt; style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); opt.rect = oRect; } #if 0 opt.features |= QStyleOptionViewItemV2::HasDisplay; QString txt = QString("%1").arg(index.isValid() ? "true" : "false"); if(index.isValid()) txt += QString(" %1 - %2").arg(index.row()).arg(view->verticalHeader()->sectionViewportPosition(index.row())); opt.text = displayText(txt, opt.locale); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); #endif // paint grid if(showGrid) { painter->save(); QPen old = painter->pen(); painter->setPen(gridPen); // qDebug() << "Paint grid for" << index.row() << "in" << opt.rect; for(int i=0; i < horizontalHeader->count(); ++i) { if(!horizontalHeader->isSectionHidden(i)) { int ofs = horizontalHeader->sectionViewportPosition(i) + viewportOffset; if(!rightToLeft) { ofs += horizontalHeader->sectionSize(i) - gridSize; } if(ofs-viewportOffset < viewport->width()) { // I have no idea, why I need to paint the grid for the selected row and the one below // but it was the only way to get this working correctly. Otherwise the grid was missing // while moving the mouse over the view from bottom to top. painter->drawLine(opt.rect.x()+ofs, opt.rect.y(), opt.rect.x()+ofs, opt.rect.height()); painter->drawLine(opt.rect.x()+ofs, opt.rect.y()+verticalHeader->sectionSize(index.row()), opt.rect.x()+ofs, opt.rect.height()); } } } painter->setPen(old); painter->restore(); } #endif }
void AlbumItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { AlbumItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) ); if ( !item ) return; QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); painter->save(); painter->setRenderHint( QPainter::Antialiasing ); if ( !( option.state & QStyle::State_Selected ) ) { QRect shadowRect = option.rect.adjusted( 5, 4, -5, -40 ); painter->setPen( QColor( 90, 90, 90 ) ); painter->drawRoundedRect( shadowRect, 0.5, 0.5 ); QPen shadowPen( QColor( 30, 30, 30 ) ); shadowPen.setWidth( 0.4 ); painter->drawLine( shadowRect.bottomLeft() + QPoint( -1, 2 ), shadowRect.bottomRight() + QPoint( 1, 2 ) ); shadowPen.setColor( QColor( 160, 160, 160 ) ); painter->setPen( shadowPen ); painter->drawLine( shadowRect.topLeft() + QPoint( -1, 2 ), shadowRect.bottomLeft() + QPoint( -1, 2 ) ); painter->drawLine( shadowRect.topRight() + QPoint( 2, 2 ), shadowRect.bottomRight() + QPoint( 2, 2 ) ); painter->drawLine( shadowRect.bottomLeft() + QPoint( 0, 3 ), shadowRect.bottomRight() + QPoint( 0, 3 ) ); shadowPen.setColor( QColor( 180, 180, 180 ) ); painter->setPen( shadowPen ); painter->drawLine( shadowRect.topLeft() + QPoint( -2, 3 ), shadowRect.bottomLeft() + QPoint( -2, 1 ) ); painter->drawLine( shadowRect.topRight() + QPoint( 3, 3 ), shadowRect.bottomRight() + QPoint( 3, 1 ) ); painter->drawLine( shadowRect.bottomLeft() + QPoint( 0, 4 ), shadowRect.bottomRight() + QPoint( 0, 4 ) ); } QPixmap cover = item->cover.isNull() ? m_defaultCover : item->cover; QRect r = option.rect.adjusted( 6, 5, -6, -41 ); if ( option.state & QStyle::State_Selected ) { #if defined(Q_WS_MAC) || defined(Q_WS_WIN) painter->save(); painter->setRenderHint( QPainter::Antialiasing ); QPainterPath border; border.addRoundedRect( r.adjusted( -2, -2, 2, 2 ), 3, 3 ); QPen borderPen( QColor( 86, 170, 243 ) ); borderPen.setWidth( 5 ); painter->setPen( borderPen ); painter->drawPath( border ); painter->restore(); #else opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) ); #endif } QPixmap scover; if ( m_cache.contains( cover.cacheKey() ) ) { scover = m_cache.value( cover.cacheKey() ); } else { scover = cover.scaled( r.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation ); m_cache.insert( cover.cacheKey(), scover ); } painter->drawPixmap( r, scover ); painter->setPen( opt.palette.color( QPalette::Text ) ); QTextOption to; to.setWrapMode( QTextOption::NoWrap ); QString text; QFont font = opt.font; font.setPixelSize( 11 ); QFont boldFont = font; boldFont.setBold( true ); QRect textRect = option.rect.adjusted( 0, option.rect.height() - 32, 0, -2 ); QString name; if ( !item->album().isNull() ) name = item->album()->name(); else if ( !item->artist().isNull() ) name = item->artist()->name(); painter->setFont( boldFont ); bool oneLiner = false; if ( item->album().isNull() || item->album()->artist().isNull() ) oneLiner = true; else oneLiner = ( textRect.height() / 2 < painter->fontMetrics().boundingRect( item->album()->name() ).height() || textRect.height() / 2 < painter->fontMetrics().boundingRect( item->album()->artist()->name() ).height() ); if ( oneLiner ) { to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); text = painter->fontMetrics().elidedText( name, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); } else { to.setAlignment( Qt::AlignHCenter | Qt::AlignTop ); text = painter->fontMetrics().elidedText( item->album()->name(), Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); // If the user is hovering over an artist rect, draw a background so she knows it's clickable QRect r = textRect; r.setTop( r.bottom() - painter->fontMetrics().height() ); r.adjust( 4, 0, -4, -1 ); if ( m_hoveringOver == index ) { TomahawkUtils::drawQueryBackground( painter, opt.palette, r, 1.5 ); painter->setPen( opt.palette.color( QPalette::HighlightedText ) ); } else { #ifdef Q_WS_MAC painter->setPen( opt.palette.color( QPalette::Dark ).darker( 200 ) ); #else painter->setPen( opt.palette.color( QPalette::Dark ) ); #endif } to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom ); text = painter->fontMetrics().elidedText( item->album()->artist()->name(), Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = r; } painter->restore(); }
/*! \reimp */ bool QCheckBox::hitButton(const QPoint &pos) const { QStyleOptionButton opt; initStyleOption(&opt); return style()->subElementRect(QStyle::SE_CheckBoxClickRect, &opt, this).contains(pos); }
void ColumnItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { PlayableItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) ); if ( !item ) return; QTextOption textOption( Qt::AlignVCenter | (Qt::Alignment)index.data( Qt::TextAlignmentRole ).toUInt() ); textOption.setWrapMode( QTextOption::NoWrap ); QString text; if ( !item->artist().isNull() ) { text = item->artist()->name(); } else if ( !item->album().isNull() ) { text = item->album()->name(); } else if ( !item->result().isNull() || !item->query().isNull() ) { float opacity = item->result() && item->result()->isOnline() ? 1.0 : 0.0; opacity = qMax( (float)0.3, opacity ); QColor textColor = TomahawkUtils::alphaBlend( option.palette.color( QPalette::Foreground ), option.palette.color( QPalette::Background ), opacity ); { QStyleOptionViewItemV4 o = option; initStyleOption( &o, QModelIndex() ); painter->save(); o.palette.setColor( QPalette::Text, textColor ); if ( m_view->currentIndex() == index ) o.state |= QStyle::State_Selected; else o.state &= ~QStyle::State_Selected; if ( o.state & QStyle::State_Selected && o.state & QStyle::State_Active ) { o.palette.setColor( QPalette::Text, o.palette.color( QPalette::HighlightedText ) ); } if ( item->isPlaying() ) { textColor = TomahawkStyle::NOW_PLAYING_ITEM_TEXT; o.palette.setColor( QPalette::Highlight, TomahawkStyle::NOW_PLAYING_ITEM ); o.palette.setColor( QPalette::Text, TomahawkStyle::NOW_PLAYING_ITEM_TEXT ); o.state |= QStyle::State_Selected; } int oldX = 0; // if ( m_view->header()->visualIndex( index.column() ) == 0 ) { oldX = o.rect.x(); o.rect.setX( 0 ); } qApp->style()->drawControl( QStyle::CE_ItemViewItem, &o, painter ); if ( oldX > 0 ) o.rect.setX( oldX ); /* if ( m_hoveringOver == index && !index.data().toString().isEmpty() && index.column() == 0 ) { o.rect.setWidth( o.rect.width() - o.rect.height() ); QRect arrowRect( o.rect.x() + o.rect.width(), o.rect.y() + 1, o.rect.height() - 2, o.rect.height() - 2 ); QPixmap infoIcon = TomahawkUtils::defaultPixmap( TomahawkUtils::InfoIcon, TomahawkUtils::Original, arrowRect.size() ); painter->drawPixmap( arrowRect, infoIcon ); m_infoButtonRects[ index ] = arrowRect; }*/ { QRect r = o.rect.adjusted( 3, 0, 0, 0 ); // Paint Now Playing Speaker Icon if ( item->isPlaying() ) { const int pixMargin = 1; const int pixHeight = r.height() - pixMargin * 2; QRect npr = r.adjusted( pixMargin, pixMargin, pixHeight - r.width() + pixMargin, -pixMargin ); painter->drawPixmap( npr, TomahawkUtils::defaultPixmap( TomahawkUtils::NowPlayingSpeaker, TomahawkUtils::Original, npr.size() ) ); r.adjust( pixHeight + 6, 0, 0, 0 ); } painter->setPen( o.palette.text().color() ); QString text = index.data().toString(); if ( item->query()->track()->albumpos() > 0 ) { text = QString( "%1. %2" ) .arg( index.data( PlayableModel::AlbumPosRole ).toString() ) .arg( index.data().toString() ); } text = painter->fontMetrics().elidedText( text, Qt::ElideRight, r.width() - 3 ); painter->drawText( r.adjusted( 0, 1, 0, 0 ), text, textOption ); } painter->restore(); } return; } else return; if ( text.trimmed().isEmpty() ) text = tr( "Unknown" ); QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); const QModelIndex curIndex = m_view->currentIndex(); if ( curIndex == index || curIndex.parent() == index || curIndex.parent().parent() == index ) opt.state |= QStyle::State_Selected; else opt.state &= ~QStyle::State_Selected; qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); if ( opt.state & QStyle::State_Selected ) { opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) ); } QRect arrowRect( m_view->viewport()->width() - option.rect.height(), option.rect.y() + 1, option.rect.height() - 2, option.rect.height() - 2 ); if ( m_hoveringOver.row() == index.row() && m_hoveringOver.parent() == index.parent() ) { QPixmap infoIcon = TomahawkUtils::defaultPixmap( TomahawkUtils::InfoIcon, TomahawkUtils::Original, arrowRect.size() ); painter->drawPixmap( arrowRect, infoIcon ); m_infoButtonRects[ index ] = arrowRect; } if ( index.column() > 0 ) return; painter->save(); painter->setRenderHint( QPainter::TextAntialiasing ); painter->setPen( opt.palette.color( QPalette::Text ) ); QRect r = option.rect.adjusted( 8, 2, -option.rect.width() + option.rect.height() + 4, -2 ); // painter->drawPixmap( r, QPixmap( RESPATH "images/cover-shadow.png" ) ); if ( !m_pixmaps.contains( index ) ) { if ( !item->album().isNull() ) { m_pixmaps.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Original, false ) ) ); _detail::Closure* closure = NewClosure( m_pixmaps[ index ], SIGNAL( repaintRequest() ), const_cast<ColumnItemDelegate*>(this), SLOT( doUpdateIndex( const QPersistentModelIndex& ) ), QPersistentModelIndex( index ) ); closure->setAutoDelete( false ); } else if ( !item->artist().isNull() )
void LevelSetDelegate::paint(QPainter* p, const QStyleOptionViewItem& opt, const QModelIndex& index) const { p->save(); QStyleOptionViewItemV4 option(opt); initStyleOption(&option, index); // // Draw item with no textwith a decoration and selection (if it's selected) // // we want to paint text by ourselves, so set it to null, paint selection and then paint text QString text = index.data(Qt::DisplayRole).toString(); option.text = QString(); option.decorationSize = QSize(48, 48); QStyle* style = QApplication::style(); style->drawControl(QStyle::CE_ItemViewItem, &option, p, 0); if (option.state & QStyle::State_Selected) p->setPen(option.palette.color(QPalette::Normal, QPalette::HighlightedText)); else p->setPen(option.palette.color(QPalette::Normal, QPalette::Text)); // // Draw text // int marginH = style->pixelMetric( QStyle::PM_FocusFrameHMargin ); int marginV = style->pixelMetric( QStyle::PM_FocusFrameVMargin ); int innerSpacing = 9; int textStartX = option.decorationSize.width() + innerSpacing; QRect r = opt.rect.adjusted(textStartX, marginV*2, 0, 0); QFontMetrics fm(opt.font); int flags = Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine; QFont font = p->font(); font.setBold(true); p->setFont(font); p->drawText(r, flags, text); // // Draw Author name // QString authorName = index.data(KAtomic::LevelSetAuthorRole).toString(); if (!authorName.isEmpty()) { if (option.state & QStyle::State_Selected) p->setPen(option.palette.color(QPalette::Disabled, QPalette::HighlightedText)); else p->setPen(option.palette.color(QPalette::Disabled, QPalette::Text)); r = r.adjusted(innerSpacing, fm.lineSpacing(), -marginH*2, 0); flags = Qt::AlignLeft | Qt::AlignTop; p->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); QString text = i18n("by %1", authorName); QString authorEmail = index.data(KAtomic::LevelSetAuthorEmailRole).toString(); if (!authorEmail.isEmpty()) text.append(QStringLiteral(" <%1>").arg(authorEmail)); int numLevels = index.data(KAtomic::LevelSetLevelCountRole).toUInt(); text.append(i18np(", contains 1 level", ", contains %1 levels", numLevels)); p->drawText(r, flags, text); } // // Draw description // QString descr = index.data(KAtomic::LevelSetDescriptionRole).toString(); if (!descr.isEmpty()) { if (option.state & QStyle::State_Selected) p->setPen(option.palette.color(QPalette::Normal, QPalette::HighlightedText)); else p->setPen(option.palette.color(QPalette::Normal, QPalette::Text)); r = opt.rect.adjusted(textStartX, fm.lineSpacing()*2, -marginH*2, -marginV*2); flags = Qt::AlignLeft | Qt::AlignBottom | Qt::TextSingleLine; p->setFont(opt.font); QString elided = fm.elidedText(descr, Qt::ElideMiddle, r.width(), flags); p->drawText(r, flags, descr); } p->restore(); }
void QgsColorRampButton::setButtonBackground( QgsColorRamp *colorramp ) { QgsColorRamp *backgroundColorRamp = colorramp; if ( !colorramp ) { backgroundColorRamp = mColorRamp; } QSize currentIconSize; //icon size is button size with a small margin if ( menu() ) { if ( !mIconSize.isValid() ) { //calculate size of push button part of widget (ie, without the menu drop-down button part) QStyleOptionToolButton opt; initStyleOption( &opt ); QRect buttonSize = QApplication::style()->subControlRect( QStyle::CC_ToolButton, &opt, QStyle::SC_ToolButton, this ); //make sure height of icon looks good under different platforms #ifdef Q_OS_WIN mIconSize = QSize( buttonSize.width() - 10, height() - 6 ); #else mIconSize = QSize( buttonSize.width() - 10, height() - 12 ); #endif } currentIconSize = mIconSize; } else { //no menu #ifdef Q_OS_WIN currentIconSize = QSize( width() - 10, height() - 6 ); #else currentIconSize = QSize( width() - 10, height() - 12 ); #endif } if ( !currentIconSize.isValid() || currentIconSize.width() <= 0 || currentIconSize.height() <= 0 ) { return; } QPixmap pm; if ( isRandomColorRamp() ) { //create a "random colors" label pm = QPixmap( currentIconSize ); pm.fill( Qt::transparent ); QPainter painter; QPen pen = ( QApplication::palette().buttonText().color() ); painter.begin( &pm ); painter.setPen( pen ); painter.drawText( QRect( 0, 0, currentIconSize.width(), currentIconSize.height() ), Qt::AlignCenter, QStringLiteral( "Random colors" ) ); painter.end(); } else { //create an icon pixmap if ( backgroundColorRamp ) { pm = QgsSymbolLayerUtils::colorRampPreviewPixmap( backgroundColorRamp, currentIconSize ); } } setIconSize( currentIconSize ); setIcon( pm ); }
// -------------------------------------------------- void ctkSearchBox::paintEvent(QPaintEvent * event) { Q_D(ctkSearchBox); // Draw the line edit with text. // Text has already been shifted to the right (in resizeEvent()) to leave // space for the search icon. this->Superclass::paintEvent(event); QPainter p(this); QRect cRect = d->clearRect(); QRect sRect = d->showSearchIcon ? d->searchRect() : QRect(); #if QT_VERSION >= 0x040700 QRect r = rect(); QPalette pal = palette(); QStyleOptionFrameV2 panel; initStyleOption(&panel); r = this->style()->subElementRect(QStyle::SE_LineEditContents, &panel, this); r.setX(r.x() + this->textMargins().left()); r.setY(r.y() + this->textMargins().top()); r.setRight(r.right() - this->textMargins().right()); r.setBottom(r.bottom() - this->textMargins().bottom()); p.setClipRect(r); QFontMetrics fm = fontMetrics(); Qt::Alignment va = QStyle::visualAlignment(this->layoutDirection(), QFlag(this->alignment())); int vscroll = 0; const int verticalMargin = 1; const int horizontalMargin = 2; switch (va & Qt::AlignVertical_Mask) { case Qt::AlignBottom: vscroll = r.y() + r.height() - fm.height() - verticalMargin; break; case Qt::AlignTop: vscroll = r.y() + verticalMargin; break; default: //center vscroll = r.y() + (r.height() - fm.height() + 1) / 2; break; } QRect lineRect(r.x() + horizontalMargin, vscroll, r.width() - 2*horizontalMargin, fm.height()); int minLB = qMax(0, -fm.minLeftBearing()); if (this->text().isEmpty()) { if (!this->hasFocus() && !this->placeholderText().isEmpty()) { QColor col = pal.text().color(); col.setAlpha(128); QPen oldpen = p.pen(); p.setPen(col); lineRect.adjust(minLB, 0, 0, 0); QString elidedText = fm.elidedText(this->placeholderText(), Qt::ElideRight, lineRect.width()); p.drawText(lineRect, va, elidedText); p.setPen(oldpen); } } p.setClipRect(this->rect()); #endif // Draw clearIcon if (!d->hideClearIcon) { QPixmap closePixmap = d->clearIcon.pixmap(cRect.size(),this->isEnabled() ? QIcon::Normal : QIcon::Disabled); this->style()->drawItemPixmap(&p, cRect, Qt::AlignCenter, closePixmap); } // Draw searchIcon if (d->showSearchIcon) { QPixmap searchPixmap = d->searchIcon.pixmap(sRect.size(), this->isEnabled() ? QIcon::Normal : QIcon::Disabled); this->style()->drawItemPixmap(&p, sRect, Qt::AlignCenter, searchPixmap); } }
QStyleOptionHeader HierarchicalHeaderView::styleOptionForCell(int logicalInd) const { QStyleOptionHeader opt; initStyleOption(&opt); if (window()->isActiveWindow()) opt.state |= QStyle::State_Active; opt.textAlignment = Qt::AlignCenter; opt.iconAlignment = Qt::AlignVCenter; opt.section = logicalInd; int visual = visualIndex(logicalInd); if (count() == 1) opt.position = QStyleOptionHeader::OnlyOneSection; else { if (visual == 0) opt.position = QStyleOptionHeader::Beginning; else opt.position=(visual==count()-1 ? QStyleOptionHeader::End : QStyleOptionHeader::Middle); } if(sectionsClickable()) { /* if (logicalIndex == d->hover) state |= QStyle::State_MouseOver; if (logicalIndex == d->pressed) { state |= QStyle::State_Sunken; } else*/ { if(highlightSections() && selectionModel()) { if(orientation()==Qt::Horizontal) { if(selectionModel()->columnIntersectsSelection(logicalInd, rootIndex())) opt.state |= QStyle::State_On; if(selectionModel()->isColumnSelected(logicalInd, rootIndex())) opt.state |= QStyle::State_Sunken; } else { if(selectionModel()->rowIntersectsSelection(logicalInd, rootIndex())) opt.state |= QStyle::State_On; if(selectionModel()->isRowSelected(logicalInd, rootIndex())) opt.state |= QStyle::State_Sunken; } } } } if(selectionModel()) { bool previousSelected=false; if(orientation()==Qt::Horizontal) previousSelected = selectionModel()->isColumnSelected(logicalIndex(visual - 1), rootIndex()); else previousSelected = selectionModel()->isRowSelected(logicalIndex(visual - 1), rootIndex()); bool nextSelected=false; if(orientation()==Qt::Horizontal) nextSelected = selectionModel()->isColumnSelected(logicalIndex(visual + 1), rootIndex()); else nextSelected = selectionModel()->isRowSelected(logicalIndex(visual + 1), rootIndex()); if (previousSelected && nextSelected) opt.selectedPosition = QStyleOptionHeader::NextAndPreviousAreSelected; else { if (previousSelected) opt.selectedPosition = QStyleOptionHeader::PreviousIsSelected; else { if (nextSelected) opt.selectedPosition = QStyleOptionHeader::NextIsSelected; else opt.selectedPosition = QStyleOptionHeader::NotAdjacent; } } } return opt; }
void SourceDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { if ( option.rect.height() == 0 ) return; QStyleOptionViewItemV4 optIndentation = option; QStyleOptionViewItemV4 opt = option; painter->save(); painter->setRenderHint( QPainter::TextAntialiasing ); painter->setRenderHint( QPainter::SmoothPixmapTransform ); const bool selected = ( option.state & QStyle::State_Selected ) == QStyle::State_Selected; if ( selected ) painter->setOpacity( 1.0 ); else painter->setOpacity( 0.7 ); SourcesModel::RowType type = static_cast< SourcesModel::RowType >( index.data( SourcesModel::SourceTreeItemTypeRole ).toInt() ); SourceTreeItem* item = index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >(); Q_ASSERT( item ); initStyleOption( &opt, index ); opt.icon = QIcon(); opt.text.clear(); // shrink the indentations { int indentMult = 0; QModelIndex counter = index; while ( counter.parent().isValid() ) { indentMult++; counter = counter.parent(); } const int indentDelta = optIndentation.rect.x() - m_parent->viewport()->x(); optIndentation.rect.setX( optIndentation.rect.x() - indentDelta + indentMult * TomahawkUtils::DpiScaler::scaledY( m_parent, TREEVIEW_INDENT_ADD ) ); opt.rect.setX( 0 ); } if ( type == SourcesModel::Source || type == SourcesModel::ScriptCollection ) { paintSource( painter, optIndentation, index ); } else if ( type == SourcesModel::Group ) { paintGroup( painter, opt, index ); } else if ( type == SourcesModel::Category ) { paintCategory( painter, optIndentation, index ); } else if ( type == SourcesModel::Divider ) { const QRect middle = optIndentation.rect.adjusted( 0, m_margin / 16, 0, -m_margin / 16 ); const QColor bgcolor = opt.palette.color( QPalette::Base ); painter->setPen( bgcolor.darker( 120 ) ); painter->drawLine( middle.topLeft(), middle.topRight() ); painter->setPen( bgcolor.lighter( 120 ) ); painter->drawLine( middle.bottomLeft(), middle.bottomRight() ); } else { optIndentation.state &= ~QStyle::State_MouseOver; if ( !index.parent().parent().isValid() ) optIndentation.rect.adjust( m_margin / 4, 0, 0, 0 ); if ( type == SourcesModel::Inbox || type == SourcesModel::Queue || type == SourcesModel::Collection ) { QString count; if ( type == SourcesModel::Inbox ) { InboxItem* ii = qobject_cast< InboxItem* >( item ); if ( ii && ii->unlistenedCount() ) count = QString::number( ii->unlistenedCount() ); } else if ( type == SourcesModel::Queue ) { QueueItem* qi = qobject_cast< QueueItem* >( item ); if ( qi && qi->unlistenedCount() ) count = QString::number( qi->unlistenedCount() ); } else if ( type == SourcesModel::Collection ) { CollectionItem* ci = qobject_cast< CollectionItem* >( item ); if ( ci ) count = QString::number( ci->trackCount() ); } paintStandardItem( painter, optIndentation, index, count ); } else if ( type == SourcesModel::TemporaryPage || type == SourcesModel::DeletablePage || type == SourcesModel::RemovablePage ) { if ( opt.state & QStyle::State_MouseOver ) { m_iconHeight = ( opt.rect.height() / 2 ); paintStandardItem( painter, optIndentation, index ); // draw close icon const QRect r( opt.rect.right() - m_margin / 8 - m_iconHeight, opt.rect.y() + ( opt.rect.height() - m_iconHeight ) / 2, m_iconHeight, m_iconHeight ); painter->drawPixmap( r, TomahawkUtils::defaultPixmap( TomahawkUtils::ListRemove, TomahawkUtils::Original, r.size() ) ); } else paintStandardItem( painter, optIndentation, index ); } else if ( type == SourcesModel::StaticPlaylist ) { paintStandardItem( painter, optIndentation, index ); PlaylistItem* plItem = qobject_cast< PlaylistItem* >( item ); if ( plItem->canSubscribe() && !plItem->subscribedIcon().isNull() ) { const int imgWidth = optIndentation.rect.height() / 2; const QPixmap icon = plItem->subscribedIcon().scaled( imgWidth, imgWidth, Qt::KeepAspectRatio, Qt::SmoothTransformation ); const QRect subRect( optIndentation.rect.right() - m_margin / 2 - imgWidth, optIndentation.rect.top() + ( optIndentation.rect.height() - imgWidth ) / 2, imgWidth, imgWidth ); painter->drawPixmap( subRect, icon ); } if ( plItem->collaborative() ) { const int imgWidth = optIndentation.rect.height() / 2; const QRect subRect( optIndentation.rect.left(), optIndentation.rect.top(), imgWidth, imgWidth ); painter->drawPixmap( subRect, TomahawkUtils::defaultPixmap( TomahawkUtils::GreenDot, TomahawkUtils::Original, subRect.size() ) ); } } else paintStandardItem( painter, optIndentation, index ); } paintDecorations( painter, opt, index ); painter->restore(); }
void TabBar::paintRectTabs(QStylePainter &p) { static const qreal penScaleFactor = 0.2; for (int i = 0; i < count(); i++) { QStyleOptionTab o; initStyleOption(&o, i); // Background color p.save(); if (i != currentIndex()) { o.rect.adjust(0, 2, 0, 0); } else if (i == count()) { o.rect.adjust(2, 2, -4, -4); } // Highlight the tab under the cursor if (o.state.testFlag(QStyle::State_MouseOver) && i != currentIndex()) { p.setPen(QPen(o.palette.highlight(), penScaleFactor)); p.fillRect(o.rect, o.palette.highlight().color().lighter()); } else { p.setPen(QPen(o.palette.mid(), penScaleFactor)); if (i == currentIndex()) { /// XXX if (SettingsPrivate::instance()->isCustomColors()) { p.fillRect(o.rect, o.palette.base().color().lighter(110)); } else { p.fillRect(o.rect, o.palette.base()); } } else { p.fillRect(o.rect, o.palette.window()); } } if (o.state.testFlag(QStyle::State_MouseOver)) { p.setPen(o.palette.highlight().color()); } else { p.setPen(o.palette.mid().color()); } // Frame tab, it is not a rectangle but only 3 lines p.drawLine(o.rect.topLeft(), o.rect.bottomLeft()); p.drawLine(o.rect.topRight(), o.rect.bottomRight()); p.drawLine(o.rect.topLeft(), o.rect.topRight()); //} p.restore(); // Icon QRect r = tabRect(i); r.setHeight(fontMetrics().ascent()); r.translate(10, (height() - r.height()) / 2); r.setWidth(r.height() / 2); p.setRenderHint(QPainter::SmoothPixmapTransform); o.icon.paint(&p, r, Qt::AlignLeft | Qt::AlignVCenter); // Playlist name if (i == currentIndex()) { p.setPen(o.palette.windowText().color()); } else if (o.state.testFlag(QStyle::State_MouseOver)) { p.setPen(o.palette.windowText().color()); } else { p.setPen(o.palette.mid().color()); } QRect rText(r.x() + r.width() + 10, r.y(), o.rect.width() - r.width() - 10, r.height()); p.drawText(rText, Qt::AlignLeft | Qt::AlignVCenter, o.text); } }
void TabBar::paintRoundedTabs(QStylePainter &p, int dist) { /// TODO: minor highlight bug when mouse goes on another tab without click // Draw all tabs before the selected tab QList<int> tabs; for (int i = 0; i < count(); i++) if (currentIndex() != i) tabs.append(i); tabs.append(currentIndex()); for (int idx = 0; idx < count(); idx++) { int i = tabs.at(idx); QStyleOptionTab o; initStyleOption(&o, i); // Background color if (i != currentIndex()) { o.rect.adjust(0, 2, 0, 0); } else if (i == count()) { o.rect.adjust(2, 2, -4, 0); } /// Adjust parameters to tighten tabs //o.rect.adjust(-dist / 2, 0, dist / 2, 0); // Rounded frame tab QPainterPath ppLeft, ppRight; ppLeft.moveTo(o.rect.x() + dist * 0, o.rect.y() + o.rect.height()); ppLeft.cubicTo(o.rect.x() + dist * 1, o.rect.y() + o.rect.height(), o.rect.x() + dist * 1, o.rect.y() + 1, o.rect.x() + dist * 2, o.rect.y() + 1); QPainterPath ppLeftCurve(ppLeft); // Add another point to be able to fill the path afterwards ppLeft.lineTo(o.rect.x() + dist * 2, o.rect.y() + o.rect.height()); QLine topHozLine(o.rect.x() + dist * 2, o.rect.y(), o.rect.x() + o.rect.width() - dist * 1, o.rect.y()); ppRight.moveTo(o.rect.x() + o.rect.width() - dist * 1, o.rect.y() + 1); ppRight.cubicTo(o.rect.x() + o.rect.width() - dist * 0, o.rect.y() + 1, o.rect.x() + o.rect.width() - dist * 0, o.rect.y() + o.rect.height(), o.rect.x() + o.rect.width() + dist * 1, o.rect.y() + o.rect.height()); QPainterPath ppRightCurve(ppRight); // Like first curve ppRight.lineTo(o.rect.x() + o.rect.width() - dist * 1, o.rect.y() + o.rect.height()); p.save(); if (o.state.testFlag(QStyle::State_MouseOver)) { p.setPen(o.palette.highlight().color()); } else { p.setPen(o.palette.mid().color()); } QRect midRect(topHozLine.p1(), QPoint(topHozLine.p2().x(), topHozLine.p2().y() + o.rect.height())); if (i == currentIndex()) { p.fillPath(ppLeft, o.palette.base()); p.fillRect(midRect, o.palette.base()); p.fillPath(ppRight, o.palette.base()); } else if (o.state.testFlag(QStyle::State_MouseOver)) { p.fillPath(ppLeft, o.palette.highlight().color().lighter()); p.fillRect(midRect, o.palette.highlight().color().lighter()); p.fillPath(ppRight, o.palette.highlight().color().lighter()); } else { p.fillPath(ppLeft, o.palette.window()); p.fillRect(midRect, o.palette.window()); p.fillPath(ppRight, o.palette.window()); } p.setRenderHint(QPainter::Antialiasing, true); p.drawPath(ppLeftCurve); p.drawPath(ppRightCurve); p.setRenderHint(QPainter::Antialiasing, false); p.drawLine(topHozLine); p.restore(); /// DEBUG //p.drawRect(o.rect); // Icon QRect r = tabRect(i); r.setHeight(fontMetrics().ascent()); r.translate(3 + dist * 1.25, (height() - r.height()) / 2); r.setWidth(r.height() / 2); p.setRenderHint(QPainter::SmoothPixmapTransform); o.icon.paint(&p, r, Qt::AlignLeft | Qt::AlignVCenter); // Playlist name if (i == currentIndex()) { p.setPen(o.palette.windowText().color()); } else if (o.state.testFlag(QStyle::State_MouseOver)) { p.setPen(o.palette.windowText().color()); } else { p.setPen(o.palette.mid().color()); } QRect rText(r.x() + r.width() + 5, this->rect().y(), o.rect.width() - (r.width() + 5), this->height() - 2); p.drawText(rText, Qt::AlignLeft | Qt::AlignVCenter, o.text); } }
/*! \reimp */ bool QGroupBox::event(QEvent *e) { Q_D(QGroupBox); #ifndef QT_NO_SHORTCUT if (e->type() == QEvent::Shortcut) { QShortcutEvent *se = static_cast<QShortcutEvent *>(e); if (se->shortcutId() == d->shortcutId) { if (!isCheckable()) { d->_q_fixFocus(Qt::ShortcutFocusReason); } else { d->click(); setFocus(Qt::ShortcutFocusReason); } return true; } } #endif QStyleOptionGroupBox box; initStyleOption(&box); switch (e->type()) { case QEvent::HoverEnter: case QEvent::HoverMove: { QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box, static_cast<QHoverEvent *>(e)->pos(), this); bool oldHover = d->hover; d->hover = d->checkable && (control == QStyle::SC_GroupBoxLabel || control == QStyle::SC_GroupBoxCheckBox); if (oldHover != d->hover) { QRect rect = style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this) | style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxLabel, this); update(rect); } return true; } case QEvent::HoverLeave: d->hover = false; if (d->checkable) { QRect rect = style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this) | style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxLabel, this); update(rect); } return true; case QEvent::KeyPress: { QKeyEvent *k = static_cast<QKeyEvent*>(e); if (!k->isAutoRepeat() && (k->key() == Qt::Key_Select || k->key() == Qt::Key_Space)) { d->pressedControl = QStyle::SC_GroupBoxCheckBox; update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this)); return true; } break; } case QEvent::KeyRelease: { QKeyEvent *k = static_cast<QKeyEvent*>(e); if (!k->isAutoRepeat() && (k->key() == Qt::Key_Select || k->key() == Qt::Key_Space)) { bool toggle = (d->pressedControl == QStyle::SC_GroupBoxLabel || d->pressedControl == QStyle::SC_GroupBoxCheckBox); d->pressedControl = QStyle::SC_None; if (toggle) d->click(); return true; } break; } default: break; } return QWidget::event(e); }
void QmlConsoleItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); painter->save(); // Set Colors QColor textColor; QIcon taskIcon; ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data( ConsoleItem::TypeRole).toInt(); switch (type) { case ConsoleItem::DebugType: textColor = QColor(CONSOLE_LOG_TEXT_COLOR); taskIcon = m_logIcon; break; case ConsoleItem::WarningType: textColor = QColor(CONSOLE_WARNING_TEXT_COLOR); taskIcon = m_warningIcon; break; case ConsoleItem::ErrorType: textColor = QColor(CONSOLE_ERROR_TEXT_COLOR); taskIcon = m_errorIcon; break; case ConsoleItem::InputType: textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR); taskIcon = m_prompt; break; default: textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR); break; } // Paint background QColor backgroundColor = drawBackground(painter, opt.rect, index, bool(opt.state & QStyle::State_Selected)); // Calculate positions const QTreeView *view = qobject_cast<const QTreeView *>(opt.widget); int level = 0; QModelIndex idx(index); while (idx.parent() != QModelIndex()) { idx = idx.parent(); level++; } int width = view->width() - level * view->indentation() - view->verticalScrollBar()->width(); bool showTypeIcon = index.parent() == QModelIndex(); bool showExpandableIcon = type == ConsoleItem::DefaultType; QRect rect(opt.rect.x(), opt.rect.top(), width, opt.rect.height()); ConsoleItemPositions positions(rect, opt.font, showTypeIcon, showExpandableIcon); // Paint TaskIconArea: if (showTypeIcon) painter->drawPixmap(positions.adjustedLeft(), positions.adjustedTop(), taskIcon.pixmap(positions.typeIconWidth(), positions.typeIconHeight())); // Set Text Color painter->setPen(textColor); // Paint TextArea: // Layout the description QString str = index.data(Qt::DisplayRole).toString(); bool showFileLineInfo = true; // show complete text if selected if (view->selectionModel()->currentIndex() == index) { QTextLayout tl(str, opt.font); layoutText(tl, positions.textAreaWidth(), &showFileLineInfo); tl.draw(painter, QPoint(positions.textAreaLeft(), positions.adjustedTop())); } else { QFontMetrics fm(opt.font); painter->drawText(positions.textArea(), fm.elidedText(str, Qt::ElideRight, positions.textAreaWidth())); } // skip if area is editable if (showExpandableIcon) { // Paint ExpandableIconArea: QIcon expandCollapseIcon; if (index.model()->rowCount(index) || index.model()->canFetchMore(index)) { if (view->isExpanded(index)) expandCollapseIcon = m_collapseIcon; else expandCollapseIcon = m_expandIcon; } painter->drawPixmap(positions.expandCollapseIconLeft(), positions.adjustedTop(), expandCollapseIcon.pixmap(positions.expandCollapseIconWidth(), positions.expandCollapseIconHeight())); } if (showFileLineInfo) { // Check for file info QString file = index.data(ConsoleItem::FileRole).toString(); const QUrl fileUrl = QUrl(file); if (fileUrl.isLocalFile()) file = fileUrl.toLocalFile(); if (!file.isEmpty()) { QFontMetrics fm(option.font); // Paint FileArea const int pos = file.lastIndexOf(QLatin1Char('/')); if (pos != -1) file = file.mid(pos +1); const int realFileWidth = fm.width(file); painter->setClipRect(positions.fileArea()); painter->drawText(positions.fileAreaLeft(), positions.adjustedTop() + fm.ascent(), file); if (realFileWidth > positions.fileAreaWidth()) { // draw a gradient to mask the text int gradientStart = positions.fileAreaLeft() - 1; QLinearGradient lg(gradientStart + ELLIPSIS_GRADIENT_WIDTH, 0, gradientStart, 0); lg.setColorAt(0, Qt::transparent); lg.setColorAt(1, backgroundColor); painter->fillRect(gradientStart, positions.adjustedTop(), ELLIPSIS_GRADIENT_WIDTH, positions.lineHeight(), lg); } // Paint LineArea QString lineText = index.data(ConsoleItem::LineRole).toString(); painter->setClipRect(positions.lineArea()); const int realLineWidth = fm.width(lineText); painter->drawText(positions.lineAreaRight() - realLineWidth, positions.adjustedTop() + fm.ascent(), lineText); } } painter->setClipRect(opt.rect); painter->restore(); }
void GrepOutputDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { // there is no function in QString to left-trim. A call to remove this this regexp does the job static const QRegExp leftspaces("^\\s*", Qt::CaseSensitive, QRegExp::RegExp); // rich text component const GrepOutputModel *model = dynamic_cast<const GrepOutputModel *>(index.model()); const GrepOutputItem *item = dynamic_cast<const GrepOutputItem *>(model->itemFromIndex(index)); QStyleOptionViewItem options = option; initStyleOption(&options, index); // building item representation QTextDocument doc; QTextCursor cur(&doc); QPalette::ColorGroup cg = options.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; QPalette::ColorRole cr = options.state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text; QTextCharFormat fmt = cur.charFormat(); fmt.setFont(options.font); if(item && item->isText()) { // Use custom manual highlighting const KTextEditor::Range rng = item->change()->m_range; // the line number appears grayed fmt.setForeground(options.palette.brush(QPalette::Disabled, cr)); cur.insertText(i18n("Line %1: ",item->lineNumber()), fmt); // switch to normal color fmt.setForeground(options.palette.brush(cg, cr)); cur.insertText(item->text().left(rng.start().column()).remove(leftspaces), fmt); fmt.setFontWeight(QFont::Bold); if ( !(options.state & QStyle::State_Selected) ) { QColor bgHighlight = option.palette.color(QPalette::AlternateBase); fmt.setBackground(bgHighlight); } cur.insertText(item->text().mid(rng.start().column(), rng.end().column() - rng.start().column()), fmt); fmt.clearBackground(); fmt.setFontWeight(QFont::Normal); cur.insertText(item->text().right(item->text().length() - rng.end().column()), fmt); }else{ QString text; if(item) text = item->text(); else text = index.data().toString(); // Simply insert the text as html. We use this for the titles. doc.setHtml(text); } painter->save(); options.text = QString(); // text will be drawn separately options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget); // set correct draw area QRect clip = options.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &options); QFontMetrics metrics(options.font); painter->translate(clip.topLeft() - QPoint(0, metrics.descent())); // We disable the clipping for now, as it leads to strange clipping errors // clip.setTopLeft(QPoint(0,0)); // painter->setClipRect(clip); QAbstractTextDocumentLayout::PaintContext ctx; // ctx.clip = clip; painter->setBackground(Qt::transparent); doc.documentLayout()->draw(painter, ctx); painter->restore(); }
void SchedulerCellDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 viewOption = option; painter->save(); QBrush brush = viewOption.backgroundBrush; QColor textColor = Qt::black; QRect rect = viewOption.rect; QString textCell = index.model()->data(index, SchedulerTableModel::WishDayRole).toString(); if (textCell == "RR") { brush = QBrush(Qt::lightGray); } else if (textCell == "XX") { textColor = Qt::white; brush = QBrush(Qt::black); // TODO: градиент как скрине // QLinearGradient gradient(rect.topLeft(), rect.bottomRight()); // gradient.setSpread(QGradient::RepeatSpread); // gradient.setColorAt(0, Qt::black); // gradient.setColorAt(1, Qt::white); // brush = QBrush(gradient); } else if (textCell == "DD") { brush = QBrush(Qt::yellow); rect.setWidth(rect.width() / 2); } else if (textCell == "NN") { brush = QBrush(Qt::yellow); rect.setX(rect.x() + rect.width() / 2); } painter->fillRect(rect, brush); DayKind day = index.model()->data(index, SchedulerTableModel::DayKindRole).value<DayKind>(); if (day != DayKind::NONE) { QImage dayImage = index.model()->data(index, SchedulerTableModel::DayImageKindRole).value<QImage>(); QRect rect = option.rect; // Отступ иконки в ячейке auto indent = 4; auto size = qMin(rect.size().width(), rect.size().height()) - indent * 2; if (!dayImage.isNull()) { dayImage = dayImage.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation); } if (isDay(day)) { painter->drawImage(rect.x() + indent, rect.y() + indent, dayImage); } else if (isNight(day)) { painter->drawImage(rect.x() + size + indent + indent * 2, rect.y() + indent, dayImage); } } // Если ячейка входит в LongRests ячейки, подрисуем снизу линию, подчеркивая ячейку const auto schedulerTableModel = dynamic_cast <const SchedulerTableModel*> (index.model()); if (schedulerTableModel && schedulerTableModel->columnInLongRests(index)) { painter->setPen(Qt::NoPen); painter->setBrush(QColor(255, 128, 0)); const auto heightLine = 4; auto rect = viewOption.rect; rect.setY(rect.y() + rect.height() - heightLine); rect.setHeight(heightLine); painter->drawRect(rect); } painter->restore(); // Цвет выделения полупрозрачный, чтобы были видно что в ячейке QStyleOptionViewItem itemOption(option); initStyleOption(&itemOption, index); if (itemOption.state & QStyle::State_Selected) { auto color = itemOption.palette.color(QPalette::Highlight); color.setAlpha(180); itemOption.palette.setColor(QPalette::Highlight, color); } // Здесь дорисовываются стандартные вещи вроде текста, которые берутся из модели QStyledItemDelegate::paint(painter, itemOption, index); }
bool SourceDelegate::editorEvent( QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index ) { QMouseEvent* mEvent = 0; switch ( event->type() ) { // case QEvent::MouseTrackingChange: case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: mEvent = static_cast< QMouseEvent* >( event ); default: break; } bool hoveringTrack = false; if ( m_trackRects.contains( index ) && mEvent ) { const QRect trackRect = m_trackRects[ index ]; hoveringTrack = trackRect.contains( mEvent->pos() ); if ( hoveringTrack ) { if ( m_trackHovered != index ) { m_trackHovered = index; QMetaObject::invokeMethod( m_parent, "update", Qt::QueuedConnection, Q_ARG( QModelIndex, index ) ); } } } if ( !hoveringTrack ) { if ( m_trackHovered.isValid() ) QMetaObject::invokeMethod( m_parent, "update", Qt::QueuedConnection, Q_ARG( QModelIndex, m_trackHovered ) ); m_trackHovered = QPersistentModelIndex(); } bool lockRectContainsClick = false, headphonesRectContainsClick = false; if ( m_headphoneRects.contains( index ) && mEvent ) { const QRect headphoneRect = m_headphoneRects[ index ]; headphonesRectContainsClick = headphoneRect.contains( mEvent->pos() ); } if ( m_lockRects.contains( index ) && mEvent ) { const QRect lockRect = m_lockRects[ index ]; lockRectContainsClick = lockRect.contains( mEvent->pos() ); } if ( event->type() == QEvent::MouseMove ) { if ( hoveringTrack || lockRectContainsClick || headphonesRectContainsClick ) m_parent->setCursor( Qt::PointingHandCursor ); else m_parent->setCursor( Qt::ArrowCursor ); } if ( event->type() == QEvent::MouseButtonRelease || event->type() == QEvent::MouseButtonPress ) { SourcesModel::RowType type = static_cast< SourcesModel::RowType >( index.data( SourcesModel::SourceTreeItemTypeRole ).toInt() ); if ( type == SourcesModel::TemporaryPage || type == SourcesModel::DeletablePage || type == SourcesModel::RemovablePage ) { SourceTreeItem* gpi = index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >(); Q_ASSERT( gpi ); QStyleOptionViewItemV4 o = option; initStyleOption( &o, index ); const int padding = m_margin / 8; const QRect r( o.rect.right() - padding - m_iconHeight, padding + o.rect.y(), m_iconHeight, m_iconHeight ); if ( r.contains( mEvent->pos() ) ) { if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { gpi->removeFromList(); // Send a new mouse event to the view, since if the mouse is now over another item's delete area we want it to show up QMouseEvent* ev = new QMouseEvent( QEvent::MouseMove, m_parent->viewport()->mapFromGlobal( QCursor::pos() ), Qt::NoButton, Qt::NoButton, Qt::NoModifier ); QApplication::postEvent( m_parent->viewport(), ev ); } return true; } } else if ( type == SourcesModel::Source ) { SourceItem* colItem = qobject_cast< SourceItem* >( index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >() ); Q_ASSERT( colItem ); if ( hoveringTrack && colItem->source() && colItem->source()->currentTrack() ) { if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { ViewManager::instance()->show( colItem->source()->currentTrack() ); return true; } else if ( event->type() == QEvent::MouseButtonPress && mEvent->button() == Qt::RightButton ) { Tomahawk::ContextMenu* contextMenu = new Tomahawk::ContextMenu( m_parent ); contextMenu->setQuery( colItem->source()->currentTrack() ); contextMenu->exec( QCursor::pos() ); return true; } } if ( !colItem->source().isNull() && !colItem->source()->currentTrack().isNull() && !colItem->source()->isLocal() ) { if ( headphonesRectContainsClick || lockRectContainsClick ) { if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { if ( headphonesRectContainsClick ) { if ( index.data( SourcesModel::LatchedOnRole ).toBool() ) // unlatch emit latchOff( colItem->source() ); else emit latchOn( colItem->source() ); } else // it's in the lock rect emit toggleRealtimeLatch( colItem->source(), !index.data( SourcesModel::LatchedRealtimeRole ).toBool() ); } return true; } } } else if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton && type == SourcesModel::StaticPlaylist ) { PlaylistItem* plItem = qobject_cast< PlaylistItem* >( index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >() ); Q_ASSERT( plItem ); if ( plItem->canSubscribe() && !plItem->subscribedIcon().isNull() ) { const int padding = m_margin / 16; const int imgWidth = option.rect.height() - 2 * padding; const QRect subRect( option.rect.right() - padding - imgWidth, option.rect.top() + padding, imgWidth, imgWidth ); if ( subRect.contains( mEvent->pos() ) ) { // Toggle playlist subscription plItem->setSubscribed( !plItem->subscribed() ); } } } } // We emit our own clicked() signal instead of relying on QTreeView's, because that is fired whether or not a delegate accepts // a mouse press event. Since we want to swallow click events when they are on headphones other action items, here we make sure we only // emit if we really want to if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { if ( m_lastClicked == -1 ) { m_lastClicked = QDateTime::currentMSecsSinceEpoch(); emit clicked( index ); } else { qint64 elapsed = QDateTime::currentMSecsSinceEpoch() - m_lastClicked; if ( elapsed < QApplication::doubleClickInterval() ) { m_lastClicked = -1; emit doubleClicked( index ); } else { m_lastClicked = QDateTime::currentMSecsSinceEpoch(); emit clicked( index ); } } } return QStyledItemDelegate::editorEvent( event, model, option, index ); }
void ScrollBar::paintEvent(QPaintEvent *) { //QScrollBar::paintEvent(e); QStylePainter p(this); QStyleOptionSlider scrollbar; initStyleOption(&scrollbar); scrollbar.palette = QApplication::palette(); QRect subLineRect = style()->subControlRect(QStyle::CC_ScrollBar, &scrollbar, QStyle::SC_ScrollBarSubLine, this); QRect addLineRect = style()->subControlRect(QStyle::CC_ScrollBar, &scrollbar, QStyle::SC_ScrollBarAddLine, this); QRect sliderRect = style()->subControlRect(QStyle::CC_ScrollBar, &scrollbar, QStyle::SC_ScrollBarSlider, this); if (orientation() == Qt::Vertical) { subLineRect.adjust(0, 0, -1, 0); addLineRect.adjust(0, 0, -1, 0); sliderRect.adjust(0, 0, -1, -1); } else { subLineRect.adjust(0, 0, 0, -1); addLineRect.adjust(0, 0, 0, -1); sliderRect.adjust(0, 0, -1, -1); } p.setPen(Qt::NoPen); p.setBrush(scrollbar.palette.window()); p.drawRect(this->rect()); p.setBrush(scrollbar.palette.base().color().darker(125)); p.drawRect(sliderRect); // Highlight p.save(); QPoint pos = mapFromGlobal(QCursor::pos()); p.setPen(scrollbar.palette.highlight().color()); if (_isDown < 0) { p.setBrush(scrollbar.palette.highlight().color().lighter()); if (subLineRect.contains(pos)) { p.drawRect(subLineRect); } else if (sliderRect.contains(pos)) { p.drawRect(sliderRect); } else if (addLineRect.contains(pos)) { p.drawRect(addLineRect); } } else { p.setBrush(scrollbar.palette.highlight().color()); if (_isDown == 0) { p.drawRect(subLineRect); } else if (_isDown == 1) { p.drawRect(sliderRect); } else if (_isDown == 2) { p.drawRect(addLineRect); } } p.restore(); // Draw sort indicator static const QPointF upArrow[3] = { QPointF(0.0, 1.0), QPointF(1.0, 0.0), QPointF(2.0, 1.0) }; static const QPointF downArrow[3] = { QPointF(0.0, 0.0), QPointF(2.0, 0.0), QPointF(1.0, 1.0) }; static const QPointF leftArrow[3] = { QPointF(0.0, 1.0), QPointF(1.0, 0.0), QPointF(1.0, 2.0) }; static const QPointF rightArrow[3] = { QPointF(0.0, 0.0), QPointF(1.0, 1.0), QPointF(0.0, 2.0) }; // Arrows p.save(); if (scrollbar.palette.windowText().color().value() < 128) { p.setPen(scrollbar.palette.dark().color()); p.setBrush(scrollbar.palette.dark()); } else { p.setPen(scrollbar.palette.mid().color()); p.setBrush(scrollbar.palette.mid()); } QTransform t; float ratio = (float) subLineRect.height() / 4.0; t.scale(ratio, ratio); if (orientation() == Qt::Vertical) { QPolygonF up, down; up.append(t.map(upArrow[0])); up.append(t.map(upArrow[1])); up.append(t.map(upArrow[2])); down.append(t.map(downArrow[0])); down.append(t.map(downArrow[1])); down.append(t.map(downArrow[2])); p.translate(subLineRect.width() / 4.0, subLineRect.height() / 3.0); p.drawPolygon(up); p.translate(0, addLineRect.y()); p.drawPolygon(down); } else { QPolygonF left, right; left.append(t.map(leftArrow[0])); left.append(t.map(leftArrow[1])); left.append(t.map(leftArrow[2])); right.append(t.map(rightArrow[0])); right.append(t.map(rightArrow[1])); right.append(t.map(rightArrow[2])); p.translate(subLineRect.height() / 3.0, subLineRect.width() / 4.0); p.drawPolygon(left); if (isLeftToRight()) { p.translate(addLineRect.x(), 0); } else { p.translate(subLineRect.x(), 0); } p.drawPolygon(right); } p.restore(); // Frame border /// FIXME bottomLeft right, topLeft topRight! p.setPen(QApplication::palette().mid().color()); if (_top) p.drawLine(rect().topLeft(), rect().topRight()); if (_bottom) p.drawLine(rect().bottomLeft(), rect().bottomRight()); if (_left) { if (isLeftToRight()) { p.drawLine(rect().topLeft(), rect().bottomLeft()); } else { p.drawLine(rect().topRight(), rect().bottomRight()); } } if (_right) { if (isLeftToRight()) { p.drawLine(rect().topRight(), rect().bottomRight()); } else { p.drawLine(rect().topLeft(), rect().bottomLeft()); } } }
void LibraryDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { //qDebug() << "LibraryDelegate::paint" << index; if (index.parent().isValid()) { painter->save(); // Split cell into two: // 1. Normal styled item // 2. Lozenge with item count / unread count // Get useful information from the index int item_count = index.data(LibraryModel::ItemCountRole).toInt(); int unread_item_count = index.data(LibraryModel::UnreadItemCountRole).toInt(); bool can_fetch_more = index.data(LibraryModel::CanFetchMoreRole).toBool(); AbstractBibliographicCollection::State state = index.data(LibraryModel::StateRole).value< AbstractBibliographicCollection::State >(); // Calculate the width of the Lozenge // w = width of text + lozenge + padding static const int padding = 1; static const int spacing = 1; QFont font(option.font); font.setPointSize(font.pointSize() - 3); font.setBold(true); QFontMetrics fontMetrics(font); QString item_count_text = QString::number(item_count) + (can_fetch_more ? "+" : ""); int item_count_lozenge_width = fontMetrics.width(item_count_text); int unread_item_count_lozenge_width = fontMetrics.width(QString::number(unread_item_count)); int lozenge_radius = qRound(option.fontMetrics.height() / 2.0) - spacing; int lozenge_height = 2 * lozenge_radius; int lozenge_width = padding + lozenge_radius + item_count_lozenge_width + lozenge_radius + padding; if (unread_item_count > 0) { lozenge_width += padding + lozenge_radius + unread_item_count_lozenge_width + lozenge_radius; } // Leave room for status icon to do its thing if (state == AbstractBibliographicCollection::BusyState) { lozenge_width += 20; } // Partition space QStyleOptionViewItemV4 option_left(option); option_left.rect.adjust(0, 0, -lozenge_width, 0); QStyleOptionViewItemV4 option_right(option); option_right.rect.setLeft(option_left.rect.right()); // Draw normal item const QStyleOptionViewItemV3 * optionV3 = qstyleoption_cast< const QStyleOptionViewItemV3 * >(&option); const QWidget * widget = optionV3 ? optionV3->widget : 0; QStyle * style = widget ? widget->style() : QApplication::style(); initStyleOption(&option_left, index); style->drawControl(QStyle::CE_ItemViewItem, &option_left, painter, widget); initStyleOption(&option_right, index); //option_right.icon = QIcon(); //option_right.text = QString(); //style->drawControl(QStyle::CE_ItemViewItem, &option_right, painter, widget); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option_right, painter, widget); // Draw item count lozenge int top = option.rect.top() + qRound((option.rect.height() - lozenge_height) / 2.0); int left = qRound(option_right.rect.left() + spacing); { QImage image(item_count_lozenge_width + 2 * lozenge_radius, lozenge_height, QImage::Format_ARGB32); image.fill(Qt::transparent); QPainterPath path; path.setFillRule(Qt::WindingFill); path.addEllipse(0, 0, lozenge_height, lozenge_height); path.addEllipse(item_count_lozenge_width, 0, lozenge_height, lozenge_height); path.addRect(lozenge_radius, 0, item_count_lozenge_width, lozenge_height); QPainter imagePainter(&image); if (option.state & QStyle::State_Selected) { imagePainter.setBrush(QColor(255, 255, 255, 200)); } else { imagePainter.setBrush(QColor(0, 0, 0, 100)); } imagePainter.setRenderHints(QPainter::Antialiasing, true); imagePainter.setPen(Qt::NoPen); imagePainter.drawPath(path); imagePainter.setCompositionMode(QPainter::CompositionMode_DestinationOut); imagePainter.setBrush(Qt::NoBrush); imagePainter.setPen(Qt::black); imagePainter.setFont(font); imagePainter.drawText(image.rect(), Qt::AlignCenter, item_count_text); painter->drawImage(left, top, image); } painter->restore(); } else if (index.isValid()) { QStyleOptionViewItem option_heading(option); option_heading.font.setPointSize(option_heading.font.pointSize() - 3); option_heading.font.setBold(true); option_heading.palette.setColor(QPalette::Text, QColor(0, 0, 0, 180)); QStyledItemDelegate::paint(painter, option_heading, index); } }
void QuickSearchItem::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); QString fileName = index.model()->data(index.model()->index(index.row(), 0)).toString(); QString filterText = index.model()->data(index.model()->index(index.row(), 2)).toString(); QIcon icon = qvariant_cast<QIcon>(index.model()->data(index.model()->index(index.row(), 1))); QRect rect = opt.rect; // draw correct background opt.text = ""; QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if (cg == QPalette::Normal && !(opt.state & QStyle::State_Active)) cg = QPalette::Inactive; // set pen color if (opt.state & QStyle::State_Selected) painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); else painter->setPen(opt.palette.color(cg, QPalette::Text)); QFont font = Tools::getInstance().defaultFont(); painter->setFont(font); QString filePart1, filePart2; filePart1 = fileName.left( fileName.indexOf(filterText) ); filePart2 = fileName.right( fileName.length() - filterText.length() - filePart1.length() ); QFontMetrics metric(font); int part1width = metric.width( filePart1 ); QFont boldFont = Tools::getInstance().defaultFont(); boldFont.setBold(true); QFontMetrics metricBold(boldFont); int boldWidth = metricBold.width( filterText ); int leftPadding = 24; painter->drawText(QRect(rect.left() + leftPadding, rect.top(), rect.width(), rect.height()), opt.displayAlignment, filePart1); painter->setFont(boldFont); painter->drawText(QRect(rect.left() + leftPadding + part1width, rect.top(), rect.width(), rect.height()), opt.displayAlignment, filterText); painter->setFont(font); painter->drawText(QRect(rect.left() + leftPadding + part1width + boldWidth, rect.top(), rect.width(), rect.height()), opt.displayAlignment, filePart2); if ( !icon.isNull() ) { QPixmap pixmap = icon.pixmap(QSize(24,24)).scaled(16, 16, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); painter->drawPixmap(rect.left() + 2, rect.top() + 2, pixmap); } }
void ListViewDelegate::paint ( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { QStyleOptionViewItemV4 opt = option; initStyleOption ( &opt, index ); painter->save(); painter->setClipRect ( opt.rect ); opt.features |= QStyleOptionViewItem::WrapText; opt.text = index.data().toString(); opt.textElideMode = Qt::ElideRight; opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); //const int iconSize = style->pixelMetric(QStyle::PM_IconViewIconSize); const int iconSize = 48; QRect iconbox = opt.rect; const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, 0, opt.widget ) + 1; QRect textRect = opt.rect; QRect textHighlightRect = textRect; // clip the decoration on top, remove width padding textRect.adjust ( textMargin,iconSize + textMargin + 5,-textMargin,0 ); textHighlightRect.adjust ( 0,iconSize + 5,0,0 ); // draw background { QSize textSize = viewItemTextSize ( &opt ); QPalette::ColorGroup cg; QStyleOptionViewItemV4 opt2(opt); if((opt.widget && opt.widget->isEnabled()) || (opt.state & QStyle::State_Enabled)) { if(! ( opt.state & QStyle::State_Active )) cg = QPalette::Inactive; else cg = QPalette::Normal; } else { cg = QPalette::Disabled; } opt2.palette.setCurrentColorGroup(cg); // fill in background, if any if ( opt.backgroundBrush.style() != Qt::NoBrush ) { QPointF oldBO = painter->brushOrigin(); painter->setBrushOrigin ( opt.rect.topLeft() ); painter->fillRect ( opt.rect, opt.backgroundBrush ); painter->setBrushOrigin ( oldBO ); } if ( opt.showDecorationSelected ) { drawSelectionRect(painter,opt2, opt.rect); drawFocusRect(painter,opt2, opt.rect); //painter->fillRect ( opt.rect, opt.palette.brush ( cg, QPalette::Highlight ) ); } else { //if ( opt.state & QStyle::State_Selected ) { //QRect textRect = subElementRect ( QStyle::SE_ItemViewItemText, opt, opt.widget ); //painter->fillRect ( textHighlightRect, opt.palette.brush ( cg, QPalette::Highlight ) ); drawSelectionRect(painter,opt2, textHighlightRect); drawFocusRect(painter,opt2, textHighlightRect); } } } // 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; iconbox.setHeight ( iconSize ); opt.icon.paint ( painter, iconbox, Qt::AlignCenter, mode, state ); } // set the text colors 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 ( opt.palette.color ( cg, QPalette::HighlightedText ) ); } else { painter->setPen ( opt.palette.color ( cg, QPalette::Text ) ); } // draw the text QTextOption textOption; textOption.setWrapMode ( QTextOption::WrapAtWordBoundaryOrAnywhere ); textOption.setTextDirection ( opt.direction ); textOption.setAlignment ( QStyle::visualAlignment ( opt.direction, opt.displayAlignment ) ); QTextLayout textLayout; textLayout.setTextOption ( textOption ); textLayout.setFont ( opt.font ); textLayout.setText ( opt.text ); qreal width, height; viewItemTextLayout ( textLayout, iconbox.width(), height, width ); const int lineCount = textLayout.lineCount(); const QRect layoutRect = QStyle::alignedRect ( opt.direction, opt.displayAlignment, QSize ( iconbox.width(), int ( height ) ), textRect ); const QPointF position = layoutRect.topLeft(); for ( int i = 0; i < lineCount; ++i ) { const QTextLine line = textLayout.lineAt ( i ); line.draw ( painter, position ); } painter->restore(); }
void QgsColorButton::setButtonBackground( const QColor &color ) { QColor backgroundColor = color; bool isProjectColor = false; if ( !backgroundColor.isValid() && !mLinkedColorName.isEmpty() ) { backgroundColor = linkedProjectColor(); isProjectColor = backgroundColor.isValid(); if ( !isProjectColor ) { mLinkedColorName.clear(); //color has been deleted, renamed, etc... emit unlinked(); } } if ( !backgroundColor.isValid() ) { backgroundColor = mColor; } QSize currentIconSize; //icon size is button size with a small margin if ( menu() ) { if ( !mIconSize.isValid() ) { //calculate size of push button part of widget (ie, without the menu drop-down button part) QStyleOptionToolButton opt; initStyleOption( &opt ); QRect buttonSize = QApplication::style()->subControlRect( QStyle::CC_ToolButton, &opt, QStyle::SC_ToolButton, this ); //make sure height of icon looks good under different platforms #ifdef Q_OS_WIN mIconSize = QSize( buttonSize.width() - 10, height() - 6 ); #else mIconSize = QSize( buttonSize.width() - 10, height() - 12 ); #endif } currentIconSize = mIconSize; } else { //no menu #ifdef Q_OS_WIN currentIconSize = QSize( width() - 10, height() - 6 ); #else currentIconSize = QSize( width() - 10, height() - 12 ); #endif } if ( !currentIconSize.isValid() || currentIconSize.width() <= 0 || currentIconSize.height() <= 0 ) { return; } //create an icon pixmap QPixmap pixmap( currentIconSize ); pixmap.fill( Qt::transparent ); if ( backgroundColor.isValid() ) { QRect rect( 0, 0, currentIconSize.width(), currentIconSize.height() ); QPainter p; p.begin( &pixmap ); p.setRenderHint( QPainter::Antialiasing ); p.setPen( Qt::NoPen ); if ( mAllowOpacity && backgroundColor.alpha() < 255 ) { //start with checkboard pattern QBrush checkBrush = QBrush( transparentBackground() ); p.setBrush( checkBrush ); p.drawRoundedRect( rect, 3, 3 ); } //draw semi-transparent color on top p.setBrush( backgroundColor ); p.drawRoundedRect( rect, 3, 3 ); p.end(); } setIconSize( currentIconSize ); setIcon( pixmap ); }
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(); // Allow a UserView's BackgroundRole to override the current theme's default color. QVariant bg = index.data(Qt::BackgroundRole); if (bg.isValid()) { painter->fillRect(option.rect, bg.value<QBrush>()); } 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(); }
void CWizUserInfoWidgetBase::paintEvent(QPaintEvent *event) { Q_UNUSED(event); int nAvatarWidth = 36; int nArrawWidth = 10; int nMargin = 4; QStyleOptionToolButton opt; initStyleOption(&opt); QPainter p(this); p.setClipRect(opt.rect); // draw user avatar QRect rectIcon = opt.rect; rectIcon.setLeft(rectIcon.left()); rectIcon.setRight(rectIcon.left() + nAvatarWidth); QPixmap pixmap = getAvatar(); if (!pixmap.isNull()) { p.drawPixmap(rectIcon, pixmap); } //if (!opt.icon.isNull()) { // opt.icon.paint(&p, rectIcon); //} // draw vip indicator QRect rectVip = rectIcon; rectVip.setLeft(rectVip.right() + nMargin); rectVip.setRight(rectVip.left() + fontMetrics().width(opt.text)); //rectVip.setBottom(rectVip.top() + rectVip.height()/2); //if (!m_iconVipIndicator.isNull()) { // m_iconVipIndicator.paint(&p, rectVip, Qt::AlignLeft|Qt::AlignTop); //} // draw display name QRect rectText = rectVip; //rectText.setBottom(rectText.bottom() + rectVip.height()); //rectText.setTop(rectText.bottom() - rectVip.height()); if (!opt.text.isEmpty()) { if (opt.state & QStyle::State_MouseOver) { QFont font = p.font(); font.setUnderline(true); p.setFont(font); } p.setPen("#787878"); // FIXME p.drawText(rectText, Qt::AlignLeft|Qt::AlignVCenter, opt.text); } // draw arraw QRect rectArrow = rectText; rectArrow.setLeft(rectArrow.right() + nMargin); rectArrow.setRight(rectArrow.left() + nArrawWidth); QIcon arrow = getArrow(); if (!arrow.isNull()) { arrow.paint(&p, rectArrow, Qt::AlignVCenter, QIcon::Normal); } }
void pTreeComboBox::calculPopupGeometry() { if ( !mView ) { return; } QStyle * const style = this->style(); // set current item and select it view()->selectionModel()->setCurrentIndex( mCurrentIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows ); QFrame* container = mFrame; QStyleOptionComboBox opt; initStyleOption( &opt ); QRect listRect( style->subControlRect( QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxListBoxPopup, this ) ); QRect screen = popupGeometry( QApplication::desktop()->screenNumber( this ) ); QPoint below = mapToGlobal( listRect.bottomLeft() ); int belowHeight = screen.bottom() -below.y(); QPoint above = mapToGlobal( listRect.topLeft() ); int aboveHeight = above.y() -screen.y(); bool boundToScreen = !window()->testAttribute( Qt::WA_DontShowOnScreen ); listRect.moveTopLeft( mapToGlobal( rect().bottomLeft() ) ); listRect.setSize( QSize( qMax( qMax( view()->viewport()->width(), mFrame->width() ), width() ) , qMax( view()->viewport()->height(), mFrame->height() ) ) ); const bool usePopup = style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ); { int listHeight = 0; int count = 0; QStack<QModelIndex> toCheck; toCheck.push( view()->rootIndex() ); #ifndef QT_NO_TREEVIEW QTreeView* treeView = qobject_cast<QTreeView*>( view() ); if ( treeView && treeView->header() && !treeView->header()->isHidden() ) listHeight += treeView->header()->height(); #endif while ( !toCheck.isEmpty() ) { QModelIndex parent = toCheck.pop(); for ( int i = 0; i < model()->rowCount( parent ); ++i ) { QModelIndex idx = model()->index( i, mModelColumn, parent ); if ( !idx.isValid() ) continue; listHeight += view()->visualRect( idx ).height(); #ifndef QT_NO_TREEVIEW if ( model()->hasChildren( idx ) && treeView && treeView->isExpanded( idx ) ) toCheck.push( idx ); #endif ++count; if ( !usePopup && count > mMaxVisibleItems ) { toCheck.clear(); break; } } } listRect.setHeight( listHeight ); } { // add the spacing for the grid on the top and the bottom; int heightMargin = 0; // add the frame of the container int marginTop, marginBottom; container->getContentsMargins( 0, &marginTop, 0, &marginBottom ); heightMargin += marginTop +marginBottom; //add the frame of the view view()->getContentsMargins( 0, &marginTop, 0, &marginBottom ); marginTop += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top*/; marginBottom += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom*/; heightMargin += marginTop +marginBottom; listRect.setHeight( listRect.height() +heightMargin ); } // Add space for margin at top and bottom if the style wants it. if ( usePopup ) listRect.setHeight( listRect.height() +style->pixelMetric( QStyle::PM_MenuVMargin, &opt, this ) *2 ); // Make sure the popup is wide enough to display its contents. if ( usePopup ) { const int diff = sizeHint().width() /*d->computeWidthHint()*/ -width(); if ( diff > 0 ) listRect.setWidth( listRect.width() +diff ); } //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show container->layout()->activate(); //takes account of the minimum/maximum size of the container listRect.setSize( listRect.size().expandedTo(container->minimumSize()) .boundedTo(container->maximumSize())); // make sure the widget fits on screen if (boundToScreen) { if (listRect.width() > screen.width() ) listRect.setWidth(screen.width()); if (/*mapToGlobal(*/listRect/*.bottomRight())*/.x() > screen.right()) { below.setX(screen.x() + screen.width() - listRect.width()); above.setX(screen.x() + screen.width() - listRect.width()); } if (/*mapToGlobal(*/listRect/*.topLeft())*/.x() < screen.x() ) { below.setX(screen.x()); above.setX(screen.x()); } } if ( usePopup ) { // Position horizontally. listRect.moveLeft( above.x() ); // Position vertically so the curently selected item lines up // with the combo box. /*const QRect currentItemRect = view()->visualRect( view()->currentIndex() ); const int offset = listRect.top() -currentItemRect.top(); listRect.moveTop( above.y() +offset -listRect.top() );*/ // Clamp the listRect height and vertical position so we don't expand outside the // available screen geometry.This may override the vertical position, but it is more // important to show as much as possible of the popup. const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height()); listRect.setHeight(height); if (boundToScreen) { if (listRect.top() < screen.top()) listRect.moveTop(screen.top()); if (listRect.bottom() > screen.bottom()) listRect.moveBottom(screen.bottom()); } } else if (!boundToScreen || listRect.height() <= belowHeight) { listRect.moveTopLeft(below); } else if (listRect.height() <= aboveHeight) { listRect.moveBottomLeft(above); } else if (belowHeight >= aboveHeight) { listRect.setHeight(belowHeight); listRect.moveTopLeft(below); } else { listRect.setHeight(aboveHeight); listRect.moveBottomLeft(above); } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #ifndef QT_NO_IM if ( QInputContext *qic = inputContext() ) qic->reset(); #endif #endif QScrollBar* sb = view()->horizontalScrollBar(); Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy(); bool needHorizontalScrollBar = ( policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn ) && sb->minimum() < sb->maximum(); if ( needHorizontalScrollBar ) { listRect.adjust( 0, 0, 0, sb->height() ); } container->setGeometry( listRect ); #ifndef Q_WS_MAC const bool updatesEnabled = container->updatesEnabled(); #endif #if defined( Q_WS_WIN ) && !defined( QT_NO_EFFECTS ) // FIXME Fix me ASAP /*bool scrollDown = ( listRect.topLeft() == below ); if ( QApplication::isEffectEnabled( Qt::UI_AnimateCombo ) && !style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) && !window()->testAttribute( Qt::WA_DontShowOnScreen ) ) qScrollEffect( container, scrollDown ? QEffects::DownScroll : QEffects::UpScroll, 150 );*/ #endif // Don't disable updates on Mac OS X. Windows are displayed immediately on this platform, // which means that the window will be visible before the call to container->show() returns. // If updates are disabled at this point we'll miss our chance at painting the popup // menu before it's shown, causing flicker since the window then displays the standard gray // background. #ifndef Q_WS_MAC container->setUpdatesEnabled( false ); #endif container->raise(); container->show(); //container->updateScrollers(); view()->setFocus(); view()->scrollTo( view()->currentIndex(), style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) ? QAbstractItemView::PositionAtCenter : QAbstractItemView::EnsureVisible ); #ifndef Q_WS_MAC container->setUpdatesEnabled( updatesEnabled ); #endif container->update(); #ifdef QT_KEYPAD_NAVIGATION if ( QApplication::keypadNavigationEnabled() ) view()->setEditFocus( true ); #endif }
/** 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(); }
void ContactDelegateCompact::paintContact(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QStyleOptionViewItemV4 optV4 = option; initStyleOption(&optV4, index); painter->save(); painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing); painter->setClipRect(optV4.rect); QStyle *style = QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter); QRect iconRect = optV4.rect; iconRect.setSize(QSize(m_avatarSize, m_avatarSize)); iconRect.moveTo(QPoint(iconRect.x() + m_spacing, iconRect.y() + m_spacing)); QPixmap avatar; avatar.load(index.data(KTp::ContactAvatarPathRole).toString()); bool noContactAvatar = avatar.isNull(); if (noContactAvatar) { avatar = SmallIcon("im-user", KIconLoader::SizeMedium); } style->drawItemPixmap(painter, iconRect, Qt::AlignCenter, avatar.scaled(iconRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); // This value is used to set the correct width for the username and the presence message. int rightIconsWidth = m_presenceIconSize + m_spacing; QPixmap icon = KIcon(index.data(KTp::ContactPresenceIconRole).toString()).pixmap(KIconLoader::SizeSmallMedium); QRect statusIconRect = optV4.rect; statusIconRect.setSize(QSize(m_presenceIconSize, m_presenceIconSize)); statusIconRect.moveTo(QPoint(optV4.rect.right() - rightIconsWidth, optV4.rect.top() + (optV4.rect.height() - m_presenceIconSize) / 2)); painter->drawPixmap(statusIconRect, icon); // Right now we only check for 'phone', as that's the most interesting type. if (index.data(KTp::ContactClientTypesRole).toStringList().contains(QLatin1String("phone"))) { // Additional space is needed for the icons, don't add too much spacing between the two icons rightIconsWidth += m_clientTypeIconSize + (m_spacing / 2); QPixmap phone = QIcon::fromTheme("phone").pixmap(m_clientTypeIconSize); QRect phoneIconRect = optV4.rect; phoneIconRect.setSize(QSize(m_clientTypeIconSize, m_clientTypeIconSize)); phoneIconRect.moveTo(QPoint(optV4.rect.right() - rightIconsWidth, optV4.rect.top() + (optV4.rect.height() - m_clientTypeIconSize) / 2)); painter->drawPixmap(phoneIconRect, phone); } QFont nameFont; if (m_listSize == ContactDelegateCompact::Mini) { nameFont = KGlobalSettings::smallestReadableFont(); } else { nameFont = KGlobalSettings::generalFont(); } const QFontMetrics nameFontMetrics(nameFont); if (option.state & QStyle::State_Selected) { painter->setPen(option.palette.color(QPalette::Active, QPalette::HighlightedText)); } else { painter->setPen(option.palette.color(QPalette::Active, QPalette::Text)); } painter->setFont(nameFont); QRect userNameRect = optV4.rect; userNameRect.setX(iconRect.x() + iconRect.width() + m_spacing * 2); userNameRect.setY(userNameRect.y() + (userNameRect.height()/2 - nameFontMetrics.height()/2)); userNameRect.setWidth(userNameRect.width() - rightIconsWidth); painter->drawText(userNameRect, nameFontMetrics.elidedText(optV4.text, Qt::ElideRight, userNameRect.width())); QRect presenceMessageRect = optV4.rect; presenceMessageRect.setX(userNameRect.x() + nameFontMetrics.boundingRect(optV4.text).width() + m_spacing * 2); presenceMessageRect.setWidth(optV4.rect.width() - presenceMessageRect.x() - rightIconsWidth); presenceMessageRect.setY(presenceMessageRect.y() + (presenceMessageRect.height()/2 - nameFontMetrics.height()/2)); if (option.state & QStyle::State_Selected) { painter->setPen(option.palette.color(QPalette::Disabled, QPalette::HighlightedText)); } else { painter->setPen(option.palette.color(QPalette::Disabled, QPalette::Text)); } painter->drawText(presenceMessageRect, nameFontMetrics.elidedText(index.data(KTp::ContactPresenceMessageRole).toString().trimmed(), Qt::ElideRight, presenceMessageRect.width())); painter->restore(); }
void AMDetailedItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt(option); initStyleOption(&opt, index); QStyle* sty = QApplication::style(); // Draw the background: (this will handle selection for us. You can also probe selection directly with opt.state & QStyle::State_Selected) sty->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter); int textStartingPoint = horizontalMargin(); // Do we have a pixmap available? QRect pmap = opt.rect; pmap.setLeft( pmap.left() + horizontalMargin() ); pmap.setTop( pmap.top() + verticalMargin() ); pmap.setBottom( pmap.bottom() - verticalMargin() ); if(opt.features & QStyleOptionViewItemV2::HasDecoration) { QPixmap p = opt.icon.pixmap(pmap.height()); sty->drawItemPixmap(painter, pmap, Qt::AlignLeft | Qt::AlignVCenter, p); textStartingPoint += horizontalMargin() + p.width() + horizontalSpacing(); } QRect textRect = opt.rect; textRect.setLeft( textRect.left() + textStartingPoint); if (index.data(AM::ModifiedRole).toBool()) { fontItalic_.setPointSize(size1_); painter->setFont(fontItalic_); } else { font_.setPointSize(size1_); painter->setFont(font_); } painter->setPen(color1_); painter->drawText(textRect, index.data(Qt::DisplayRole).toString()); QVariant description = index.data(AM::DescriptionRole); if(!description.isNull()){ font_.setPointSize(size2_); painter->setFont(font_); painter->setPen(color2_); QFontMetrics fontMetrics(font_); painter->drawText(textRect.translated(QPoint(0,20)), fontMetrics.elidedText(description.toString(), Qt::ElideRight, textRect.width() )); } /// call base class to draw close button: drawCloseButton(painter, opt, index); /* What info is available: enum OptionType enum Position enum StyleOptionType enum StyleOptionVersion enum ViewItemFeature flags ViewItemFeatures enum ViewItemPosition QStyleOptionViewItemV4 () QStyleOptionViewItemV4 ( const QStyleOptionViewItemV4 & ) QStyleOptionViewItemV4 ( const QStyleOptionViewItem & ) backgroundBrush : QBrush checkState : Qt::CheckState decorationAlignment : Qt::Alignment decorationPosition : Position decorationSize : QSize direction : Qt::LayoutDirection displayAlignment : Qt::Alignment features : ViewItemFeatures font : QFont fontMetrics : QFontMetrics icon : QIcon index : QModelIndex initFrom ( const QWidget * ) locale : QLocale palette : QPalette rect : QRect showDecorationSelected : bool state : QStyle::State text : QString textElideMode : Qt::TextElideMode type : int version : int viewItemPosition : ViewItemPosition widget : const QWidget * operator= ( const QStyleOptionViewItem & ) : QStyleOption */ }
virtual void paintEvent(QPaintEvent *ev) { if (tickPosition() == QSlider::NoTicks) return QSlider::paintEvent(ev); QPainter p(this); QStyleOptionSlider option; initStyleOption(&option); const int& ticks( option.tickPosition ); const int available(style()->proxy()->pixelMetric(QStyle::PM_SliderSpaceAvailable, &option, this)); int interval = option.tickInterval; if( interval < 1 ) interval = option.pageStep; if( interval < 1 ) return; const QRect& r(option.rect); const QPalette palette(option.palette); const int fudge(style()->proxy()->pixelMetric(QStyle::PM_SliderLength, &option, this) / 2); int current(option.minimum); int nextLabel = current; QFontMetrics fm(font()); int h = fm.height() + 3; int w = fm.width(QString::number(option.maximum)) + 3; if(available<w) nextLabel = -1; float i = available/(orientation() == Qt::Horizontal ? w : h); float t = option.maximum/interval; int valStep = t/ i + 1; // Since there is no subrect for tickmarks do a translation here. p.save(); p.translate(r.x(), r.y()); p.setPen(palette.color(QPalette::WindowText)); int extra = (option.tickPosition == QSlider::TicksBothSides ? 2 : 1); int tickSize(option.orientation == Qt::Horizontal ? (r.height() - h*extra)/3:(r.width() - w*extra)/3); while(current <= option.maximum) { const int position(QStyle::sliderPositionFromValue(option.minimum, option.maximum, current, available, option.upsideDown) + fudge); // calculate positions if(option.orientation == Qt::Horizontal) { if (ticks & QSlider::TicksAbove) { p.drawLine(position, h, position, tickSize + h); if(current == nextLabel) p.drawText(QRect(position - w/2, 0, w, h), Qt::AlignHCenter, QString::number(current)); } if (ticks & QSlider::TicksBelow) { p.drawLine( position, r.height() - h - tickSize, position, r.height() - h ); if(current == nextLabel) p.drawText(QRect(position - w/2, r.height() - h + 3, w, h), Qt::AlignHCenter, QString::number(current)); } } else { if (ticks & QSlider::TicksAbove) { p.drawLine(w, position, tickSize + w, position); if(current == nextLabel) p.drawText(QRect(0, position - h/2, w - 3, h), Qt::AlignRight | Qt::AlignVCenter, QString::number(current)); } if (ticks & QSlider::TicksBelow) { p.drawLine(r.width() - w - tickSize, position, r.width() - w, position ); if(current == nextLabel) p.drawText(QRect(r.width() - w + 3, position - h/2, w, h), Qt::AlignVCenter, QString::number(current)); } } // go to next position if (current == nextLabel) nextLabel += interval*valStep; current += interval; } p.restore(); option.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle; style()->proxy()->drawComplexControl(QStyle::CC_Slider, &option, &p, this); }
/** ***************************************************************************/ void ProposalList::ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &options, const QModelIndex &index) const { painter->save(); QStyleOptionViewItem option = options; initStyleOption(&option, index); /* * fm(x) := fontmetrics of x * DR := DisplayRole * TR := ToolTipRole * +---------------------+----------------------------------------+ * | | | * | +-------------+ | | * | | | | | * | | | |a*fm(DR)/(fm(DR)+fm(TR)) DisplayRole | * a| | icon | | | * | | | | | * | | | +----------------------------------------+ * | | | | | * | +-------------+ |a*fm(TR)/(fm(DR)+fm(TR)) ToolTipRole+x | * | | | * +---------------------------------------------------------------+ */ // Avoid ugly dark blue mouseover background // TODO: QT_MINREL 5.7 setFlag option.state &= ~QStyle::State_MouseOver; // Draw selection option.widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, option.widget); // Draw icon if ( drawIcon ){ QRect iconRect = QRect( QPoint((option.rect.height() - option.decorationSize.width())/2 + option.rect.x(), (option.rect.height() - option.decorationSize.height())/2 + option.rect.y()), option.decorationSize); QPixmap pixmap; QString iconPath = index.data(Qt::DecorationRole).value<QString>(); QString cacheKey = QString("%1%2%3").arg(option.decorationSize.width(), option.decorationSize.height()).arg(iconPath); if ( !QPixmapCache::find(cacheKey, &pixmap) ) { pixmap = QPixmap(iconPath).scaled(option.decorationSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPixmapCache::insert(cacheKey, pixmap); } painter->drawPixmap(iconRect, pixmap); } // Calculate text rects QFont font1 = option.font; QFont font2 = option.font; font2.setPixelSize(12); QFontMetrics fontMetrics1 = QFontMetrics(font1); QFontMetrics fontMetrics2 = QFontMetrics(font2); QRect contentRect = option.rect; contentRect.setLeft(drawIcon ? option.rect.height() : 0); contentRect.setTop(option.rect.y()+option.rect.height()/2-(fontMetrics1.height()+fontMetrics2.height())/2); contentRect.setBottom(option.rect.y()+option.rect.height()/2+(fontMetrics1.height()+fontMetrics2.height())/2); QRect textRect = contentRect.adjusted(0,-2,0,-fontMetrics2.height()-2); QRect subTextRect = contentRect.adjusted(0,fontMetrics1.height()-2,0,-2); // // Test // painter->fillRect(iconRect, Qt::magenta); // painter->fillRect(contentRect, Qt::red); // painter->fillRect(textRect, Qt::blue); // painter->fillRect(subTextRect, Qt::yellow); // Draw display role painter->setFont(font1); QString text = fontMetrics1.elidedText(index.data(Qt::DisplayRole).toString(), option.textElideMode, textRect.width()); option.widget->style()->drawItemText(painter, textRect, option.displayAlignment, option.palette, option.state & QStyle::State_Enabled, text, (option.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::WindowText); // Draw tooltip role painter->setFont(font2); text = fontMetrics2.elidedText(index.data(option.state.testFlag(QStyle::State_Selected)? subTextRole : Qt::ToolTipRole).toString(), option.textElideMode, subTextRect.width()); option.widget->style()->drawItemText(painter, subTextRect, Qt::AlignBottom|Qt::AlignLeft, option.palette, option.state & QStyle::State_Enabled, text, (option.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::WindowText); painter->restore(); }
void QgsCollapsibleGroupBox::updateStyle() { setUpdatesEnabled( false ); // margin/offset defaults int marginLeft = 20; // title margin for disclosure triangle int marginRight = 5; // a little bit of space on the right, to match space on the left int offsetLeft = 0; // offset for oxygen theme int offsetTop = 0; int offsetTop2 = 0; // offset for triangle // calculate offset if frame overlaps triangle (oxygen theme) // using an offset of 6 pixels from frame border if ( QApplication::style()->objectName().toLower() == "oxygen" ) { QStyleOptionGroupBox box; initStyleOption( &box ); QRect rectFrame = style()->subControlRect( QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxFrame, this ); QRect rectCheckBox = style()->subControlRect( QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this ); if ( rectFrame.left() <= 0 ) offsetLeft = 6 + rectFrame.left(); if ( rectFrame.top() <= 0 ) { if ( isCheckable() ) { // if is checkable align with checkbox offsetTop = ( rectCheckBox.height() / 2 ) - ( mCollapseButton->height() / 2 ) + rectCheckBox.top(); offsetTop2 = offsetTop + 1; } else { offsetTop = 6 + rectFrame.top(); offsetTop2 = offsetTop; } } } QgsDebugMsg( QString( "groupbox: %1 style: %2 offset: left=%3 top=%4 top2=%5" ).arg( objectName() ).arg( QApplication::style()->objectName() ).arg( offsetLeft ).arg( offsetTop ).arg( offsetTop2 ) ); // customize style sheet for collapse/expand button and force left-aligned title // TODO: move to app stylesheet system, when appropriate QString ss; ss += "QgsCollapsibleGroupBox::title {"; ss += " subcontrol-origin: margin;"; ss += " subcontrol-position: top left;"; ss += QString( " margin-left: %1px;" ).arg( marginLeft ); ss += QString( " margin-right: %1px;" ).arg( marginRight ); ss += QString( " left: %1px;" ).arg( offsetLeft ); ss += QString( " top: %1px;" ).arg( offsetTop ); ss += "}"; setStyleSheet( ss ); // clear toolbutton default background and border and apply offset QString ssd; ssd = QString( "QgsCollapsibleGroupBox > QToolButton#%1 {" ).arg( mCollapseButton->objectName() ); ssd += " background-color: rgba(255, 255, 255, 0); border: none;"; ssd += "}"; mCollapseButton->setStyleSheet( ssd ); if ( offsetLeft != 0 || offsetTop2 != 0 ) mCollapseButton->move( offsetLeft, offsetTop2 ); setUpdatesEnabled( true ); }