void Text::layout1() { if (styled() && !_editMode) SimpleText::layout(); else { _doc->setDefaultFont(textStyle().font(spatium())); qreal w = -1.0; QPointF o(textStyle().offset(spatium())); if (parent() && layoutToParentWidth()) { Element* e = parent(); w = e->width(); if (e->type() == HBOX || e->type() == VBOX || e->type() == TBOX) { Box* b = static_cast<Box*>(e); w -= ((b->leftMargin() + b->rightMargin()) * MScore::DPMM); } } QTextOption to = _doc->defaultTextOption(); to.setUseDesignMetrics(true); to.setWrapMode(w <= 0.0 ? QTextOption::NoWrap : QTextOption::WrapAtWordBoundaryOrAnywhere); _doc->setDefaultTextOption(to); if (w <= 0.0) w = _doc->idealWidth(); _doc->setTextWidth(w); QSizeF size(_doc->size()); if (align() & ALIGN_BOTTOM) o.ry() -= size.height(); else if (align() & ALIGN_VCENTER) o.ry() -= (size.height() * .5); else if (align() & ALIGN_BASELINE) o.ry() -= baseLine(); if (align() & ALIGN_RIGHT) o.rx() -= size.width(); else if (align() & ALIGN_HCENTER) o.rx() -= (size.width() * .5); setbbox(QRectF(QPointF(0.0, 0.0), size)); _doc->setModified(false); setPos(o); } if (parent()) { Element* e = parent(); qreal w, h, xo, yo; if (layoutToParentWidth()) { if (e->type() == HBOX || e->type() == VBOX || e->type() == TBOX) { // consider inner margins of frame Box* b = static_cast<Box*>(e); xo = b->leftMargin() * MScore::DPMM; yo = b->topMargin() * MScore::DPMM; w = b->width() - xo - b->rightMargin() * MScore::DPMM; h = b->height() - yo - b->bottomMargin() * MScore::DPMM; } else { w = e->width(); h = e->height(); xo = 0.0; yo = 0.0; } QPointF ro(_textStyle.reloff() * .01); rxpos() += xo + ro.x() * w; rypos() += yo + ro.y() * h; } if (e->type() == SEGMENT) { Segment* s = static_cast<Segment*>(e); rypos() += s->measure()->system()->staff(staffIdx())->y(); } } if (hasFrame()) layoutFrame(); }
void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const { Q_ASSERT(layout); layout->setText(data(MessageModel::DisplayRole).toString()); QTextOption option; option.setWrapMode(wrapMode); option.setAlignment(alignment); layout->setTextOption(option); QList<QTextLayout::FormatRange> formatRanges = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt()); layout->setAdditionalFormats(formatRanges); }
StyledLabel::StyledLabel(QWidget *parent) : QFrame(parent), _wrapMode(QTextOption::NoWrap), _alignment(Qt::AlignVCenter|Qt::AlignLeft), _toolTipEnabled(true), _resizeMode(NoResize) { setMouseTracking(true); QTextOption opt = _layout.textOption(); opt.setWrapMode(_wrapMode); opt.setAlignment(_alignment); _layout.setTextOption(opt); }
ItemSync::ItemSync(const QString &label, const QString &icon, ItemWidget *childItem) : QWidget( childItem->widget()->parentWidget() ) , ItemWidgetWrapper(childItem, this) , m_label( new QTextEdit(this) ) , m_icon( new IconWidget(icon, this) ) { auto layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->setSizeConstraint(QLayout::SetMinimumSize); auto labelLayout = new QHBoxLayout; connect( layout, &QVBoxLayout::destroyed, labelLayout, &QHBoxLayout::deleteLater ); labelLayout->setContentsMargins(0, 0, 0, 0); labelLayout->setSpacing(0); labelLayout->addWidget(m_icon); labelLayout->addWidget(m_label); labelLayout->addStretch(); layout->addLayout(labelLayout); QWidget *w = childItem->widget(); layout->addWidget(w); w->setObjectName("item_child"); w->setParent(this); m_label->setObjectName("item_child"); m_label->document()->setDefaultFont(font()); QTextOption option = m_label->document()->defaultTextOption(); option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); m_label->document()->setDefaultTextOption(option); m_label->setReadOnly(true); m_label->setUndoRedoEnabled(false); m_label->setFocusPolicy(Qt::NoFocus); m_label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_label->setFrameStyle(QFrame::NoFrame); m_label->setContextMenuPolicy(Qt::NoContextMenu); m_label->viewport()->installEventFilter(this); m_label->setPlainText(label); }
QSizeF QwtRichTextEngine::textSize( const QFont &font, int flags, const QString& text ) const { QwtRichTextDocument doc( text, flags, font ); QTextOption option = doc.defaultTextOption(); if ( option.wrapMode() != QTextOption::NoWrap ) { option.setWrapMode( QTextOption::NoWrap ); doc.setDefaultTextOption( option ); doc.adjustSize(); } return doc.size(); }
void PsiTipLabel::initUi() { margin = 1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, nullptr, this); setFrameStyle(QFrame::NoFrame); doc = new QTextDocument(this); QTextOption opt = doc->defaultTextOption(); opt.setWrapMode(QTextOption::WordWrap); doc->setDefaultTextOption(opt); doc->setUndoRedoEnabled(false); doc->setDefaultFont(font()); ensurePolished(); setText(theText_); }
void FormEditorItem::paintPlaceHolderForInvisbleItem(QPainter *painter) const { qreal stripesWidth = 12; QRegion innerRegion = QRegion(boundingRect().adjusted(stripesWidth, stripesWidth, -stripesWidth, -stripesWidth).toRect()); QRegion outerRegion = QRegion(boundingRect().toRect()) - innerRegion; painter->setClipRegion(outerRegion); painter->setClipping(true); painter->fillRect(boundingRect().adjusted(1, 1, -1, -1), Qt::BDiagPattern); painter->setClipping(false); QString displayText = qmlItemNode().id(); if (displayText.isEmpty()) displayText = qmlItemNode().simplifiedTypeName(); QTextOption textOption; textOption.setAlignment(Qt::AlignCenter); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); if (boundingRect().width() > 60) { painter->save(); QFont font; font.setStyleHint(QFont::SansSerif); font.setBold(true); font.setPixelSize(14); painter->setFont(font); QFontMetrics fm(font); if (fm.width(displayText) > (boundingRect().width() - 22) && displayText.length() > 4) { displayText = fm.elidedText(displayText, Qt::ElideRight, boundingRect().width() - 22, Qt::TextShowMnemonic); } painter->setPen(QColor(255, 255, 255, 128)); painter->setCompositionMode(QPainter::CompositionMode_Exclusion); painter->drawText(boundingRect().adjusted(-2, -2, 0,0), displayText, textOption); painter->setFont(font); painter->setPen(QColor(0, 0, 0, 255)); painter->drawText(boundingRect(), displayText, textOption); painter->restore(); } }
static QSize viewItemTextSize ( const QStyleOptionViewItemV4 *option ) { QStyle *style = option->widget ? option->widget->style() : QApplication::style(); QTextOption textOption; textOption.setWrapMode ( QTextOption::WrapAtWordBoundaryOrAnywhere ); QTextLayout textLayout; textLayout.setTextOption ( textOption ); textLayout.setFont ( option->font ); textLayout.setText ( option->text ); const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, option, option->widget ) + 1; QRect bounds ( 0,0,100 - 2*textMargin,600 ); qreal height = 0, widthUsed = 0; viewItemTextLayout ( textLayout, bounds.width(), height, widthUsed ); const QSize size ( qCeil ( widthUsed ), qCeil ( height ) ); return QSize ( size.width() + 2 * textMargin, size.height() ); }
QStaticText ApiTraceFrame::staticText() const { if (!m_staticText.text().isEmpty()) return m_staticText; QString richText = QString::fromLatin1("<span style=\"font-weight:bold\">Frame %1</span>").arg(number); m_staticText.setText(richText); QTextOption opt; opt.setWrapMode(QTextOption::NoWrap); m_staticText.setTextOption(opt); m_staticText.prepare(); return m_staticText; }
void Text::regenerate() { if (!doc) { doc = DocumentCache::getInstance().pop(); dirty = true; } if (dirty) { doc->setDefaultFont(defFont); if (elide) { QFontMetrics metrics = QFontMetrics(defFont); QString elidedText = metrics.elidedText(text, Qt::ElideRight, qRound(width)); doc->setPlainText(elidedText); } else { doc->setDefaultStyleSheet(defStyleSheet); doc->setHtml(text); } // wrap mode QTextOption opt; opt.setWrapMode(elide ? QTextOption::NoWrap : QTextOption::WrapAtWordBoundaryOrAnywhere); doc->setDefaultTextOption(opt); // width doc->setTextWidth(width); doc->documentLayout()->update(); // update ascent if (doc->firstBlock().layout()->lineCount() > 0) ascent = doc->firstBlock().layout()->lineAt(0).ascent(); // let the scene know about our change in size if (size != idealSize()) prepareGeometryChange(); // get the new width and height size = idealSize(); dirty = false; } // if we are not visible -> free mem if (!keepInMemory) freeResources(); }
void TextItem::init() { setTextInteractionFlags(Qt::TextEditorInteraction); setFlag(ItemIsSelectable, true); setFlag(ItemIsFocusable, true); QTextOption options; options.setWrapMode(QTextOption::NoWrap); options.setAlignment(Qt::AlignCenter); document()->setDefaultTextOption(options); connect(document(), &QTextDocument::contentsChanged, this, &TextItem::checkText); QFont f = font(); f.setPixelSize(13); setFont(f); }
void PrintOut::addBox(int percent, const QString &text, Style style, Qt::Alignment halign) { QTextOption options; options.setAlignment(halign | Qt::AlignTop); options.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); QFont f = f10; if (style == Strong) f.setBold(true); else if (style == Emphasis) f.setItalic(true); int wd = hsize * percent / 100; QRect r(cp.rect.x() + cp.rect.width(), 0, wd, vsize); const int ht = static_cast<int>(p.boundingRect(r, text, options).height()); Box b(r, text, f, options); cp.boxes.append(b); cp.rect.setSize(QSize(cp.rect.width() + wd, qMax(cp.rect.height(), ht))); }
void render_sequence( QPainter * painter, const QStyleOptionViewItem& option, const QString& text ) const { painter->save(); QStyleOptionViewItemV4 op = option; QTextDocument document; QTextOption to; to.setWrapMode( QTextOption::WrapAtWordBoundaryOrAnywhere ); document.setDefaultTextOption( to ); QFont font; font.setFamily( "Consolas" ); document.setDefaultFont( font ); document.setTextWidth( op.rect.width() ); document.setHtml( text ); op.widget->style()->drawControl( QStyle::CE_ItemViewItem, &op, painter ); painter->translate( op.rect.topLeft() ); QRect clip( 0, 0, op.rect.width(), op.rect.height() ); document.drawContents( painter, clip ); painter->restore(); }
void FlightItem::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); const int i = (m_landscape ? 1 : 0); painter.setPen(palette().color(QPalette::BrightText)); painter.drawText(QRect(columns[i][0] - 2, 0, columns[i][1] - columns[i][0], height()), m_scheduleTime.time().toString("hhmm")); painter.drawText(QRect(columns[i][1] - 2, 0, columns[i][2] - columns[i][1], height()), m_flightID); if (m_direction == FlightTimes::Arrivals) painter.drawText(QRect(columns[i][2] - 2, 0, columns[i][3] - columns[i][2], height()), m_beltNumber); else painter.drawText(QRect(columns[i][2] - 2, 0, columns[i][3] - columns[i][2], height()), m_gate); QTextOption option; option.setWrapMode(QTextOption::NoWrap); const QString name = (m_routeAirportNames.isEmpty() ? m_airportName : m_routeAirportNames); int last = width() > columns[i][5] ? columns[i][5] : columns[i][4]; painter.drawText(QRect(columns[i][3] - 2, 0, last - columns[i][3], height()), fontMetrics().elidedText(name, Qt::ElideRight, last - columns[i][3]), option); painter.drawText(QRect(last - 2, 0, width() - last, height()), m_statusText, option); }
QStaticText ApiTraceCall::staticText() const { if (!m_staticText.text().isEmpty()) return m_staticText; QString richText = QString::fromLatin1("<span style=\"font-weight:bold\">%1</span>(").arg(name); for (int i = 0; i < argNames.count(); ++i) { richText += QLatin1String("<span style=\"color:#0000ff\">"); QString argText = apiVariantToString(argValues[i]); //if arguments are really long (e.g. shader text), cut them // and elide it if (argText.length() > 40) { QString shortened = argText.mid(0, 40); shortened[argText.length() - 5] = '.'; shortened[argText.length() - 4] = '.'; shortened[argText.length() - 3] = '.'; shortened[argText.length() - 2] = argText[argText.length() - 2]; shortened[argText.length() - 1] = argText[argText.length() - 1]; richText += shortened; } else { richText += argText; } richText += QLatin1String("</span>"); if (i < argNames.count() - 1) richText += QString::fromLatin1(", "); } richText += QLatin1String(")"); if (returnValue.isValid()) { richText += QLatin1String(" = "); richText += QLatin1String("<span style=\"color:#0000ff\">"); richText += apiVariantToString(returnValue); richText += QLatin1String("</span>"); } m_staticText.setText(richText); QTextOption opt; opt.setWrapMode(QTextOption::NoWrap); m_staticText.setTextOption(opt); m_staticText.prepare(); return m_staticText; }
void HelpWidget::paintEvent(QPaintEvent* e) { Q_UNUSED(e); QRectF r = rect().adjusted(1, 1, -1, -1); QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.setPen(QColor(187, 174, 105)); p.setBrush(QColor(242, 238, 184)); p.drawRoundedRect(r, 4, 4); p.setPen(QColor(104, 74, 64)); p.setFont(mFont); QTextOption options; options.setWrapMode(QTextOption::WordWrap); options.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); p.drawText(rect().adjusted(5, 5, -5, -5), mText, options); }
void SenderChatItem::initDocument(QTextDocument *doc) { // Hide double sender names QModelIndex lastIndex = model()->index(row()-1, column()); if (lastIndex.isValid() && data(MessageModel::TypeRole).toInt() == Message::Plain && model()->data(lastIndex, MessageModel::TypeRole).toInt() == Message::Plain && (data(MessageModel::FlagsRole).toInt() & Message::Self) == (model()->data(lastIndex, MessageModel::FlagsRole).toInt() & Message::Self)) { doc->setPlainText(""); } else { doc->setPlainText(data(MessageModel::DisplayRole).toString()); } doc->setTextWidth(width()); QTextOption o; o.setWrapMode(QTextOption::NoWrap); doc->setDefaultTextOption(o); }
//virtual void PageTab::redoLabelTextLayout() { //TODO: somewhat wasteful. If there is no label, should just exit early and leave a layout that will be left unrendered by paint() m_textLayoutObject.clearLayout();; //TODO: Need a real fix later instead of localizing the labels at runtime QString m_tabLabelLocalized = fromStdUtf8(LOCALIZED(m_tabLabel.toStdString())); m_textLayoutObject.setText(m_tabLabelLocalized); // int fontSize = qBound(4,(int)((qreal)(m_labelMaxGeom.height())*0.5),24) -2; // fontSize = fontSize - (fontSize % 2); // m_textFont.setPixelSize(fontSize); m_textLayoutObject.setFont(m_textFont); QTextOption textOpts; textOpts.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); textOpts.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); m_textLayoutObject.setTextOption(textOpts); QFontMetrics textFontMetrics(m_textFont); int leading = textFontMetrics.leading(); int rise = textFontMetrics.ascent(); qreal height = 0; m_textLayoutObject.beginLayout(); while (height < m_labelMaxGeom.height()) { QTextLine line = m_textLayoutObject.createLine(); if (!line.isValid()) break; line.setLineWidth(m_labelMaxGeom.width()); if (m_textLayoutObject.lineCount() > 1) { height += leading; } line.setPosition(QPointF(0, height)); height += line.height(); } height = qMin((quint32)DimensionsGlobal::roundUp(height),(quint32)m_labelMaxGeom.height()); height = DimensionsGlobal::roundDown(height) - (DimensionsGlobal::roundDown(height) % 2); //force to an even # m_textLayoutObject.endLayout(); //TODO: PIXEL-ALIGN m_labelGeom = DimensionsGlobal::realRectAroundRealPoint(QSizeF(m_textLayoutObject.boundingRect().width(),height)).toAlignedRect(); }
static PyObject *meth_QTextOption_setWrapMode(PyObject *sipSelf, PyObject *sipArgs) { PyObject *sipParseErr = NULL; { QTextOption::WrapMode a0; QTextOption *sipCpp; if (sipParseArgs(&sipParseErr, sipArgs, "BE", &sipSelf, sipType_QTextOption, &sipCpp, sipType_QTextOption_WrapMode, &a0)) { sipCpp->setWrapMode(a0); Py_INCREF(Py_None); return Py_None; } } /* Raise an exception if the arguments couldn't be parsed. */ sipNoMethod(sipParseErr, sipName_QTextOption, sipName_setWrapMode, doc_QTextOption_setWrapMode); return NULL; }
QTextDocument *TalkablePainter::createDescriptionDocument(const QString &text, int width, QColor color) const { QString description = Qt::escape(text).replace( '\n', Configuration->showMultiLineDescription() ? QStringLiteral("<br/>") : QStringLiteral(" ")); QTextDocument *const doc = new QTextDocument(); doc->setDefaultFont(Configuration->descriptionFont()); if (color.isValid()) doc->setDefaultStyleSheet(QString("* { color: %1; }").arg(color.name())); doc->setHtml(QString("<span>%1</span>").arg(description)); QTextOption opt = doc->defaultTextOption(); opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); doc->setDefaultTextOption(opt); QTextFrameFormat frameFormat = doc->rootFrame()->frameFormat(); frameFormat.setMargin(0); doc->rootFrame()->setFrameFormat(frameFormat); doc->setTextWidth(width); return doc; }
Text::Text(Score* s) : Element(s) { #if 0 _doc = new QTextDocument(0); _doc->setDocumentMargin(1.0); _doc->setUseDesignMetrics(true); _doc->setUndoRedoEnabled(true); QTextOption to = _doc->defaultTextOption(); to.setUseDesignMetrics(true); to.setWrapMode(QTextOption::NoWrap); _doc->setDefaultTextOption(to); #endif setFlag(ELEMENT_MOVABLE, true); _textStyle = TEXT_STYLE_INVALID; _styled = false; _layoutToParentWidth = false; setSubtype(0); _lineSpacing = 0.0; _lineHeight = 0.0; _baseLine = 0.0; }
void AppItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.data(AppsListModel::AppItemIsDragingRole).value<bool>() && !(option.features & QStyleOptionViewItem::HasDisplay)) return; painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform); painter->setPen(Qt::white); painter->setBrush(QBrush(Qt::transparent)); const int leftMargin = 2, radius = 3; const int fontPixelSize = index.data(AppsListModel::AppFontSizeRole).value<int>(); const bool drawBlueDot = index.data(AppsListModel::AppNewInstallRole).toBool(); const ItemInfo itemInfo = index.data(AppsListModel::AppRawItemInfoRole).value<ItemInfo>(); const QRect boundingRect = itemBoundingRect(option.rect); const QSize iconSize = index.data(AppsListModel::AppIconSizeRole).toSize(); // draw focus background if (CurrentIndex == index && !(option.features & QStyleOptionViewItem::HasDisplay)) { const QColor borderColor(255, 255, 255, 52); const QColor brushColor(0, 0, 0, 105); QPen pen; pen.setColor(borderColor); pen.setWidth(2); QPainterPath border; border.addRoundedRect(boundingRect.marginsRemoved(QMargins(leftMargin/2, leftMargin/2, leftMargin*2/3, leftMargin*2/3)), radius, radius); painter->strokePath(border, pen); painter->setPen(Qt::transparent); painter->setBrush(brushColor); painter->drawRoundedRect(boundingRect.marginsRemoved(QMargins(leftMargin, leftMargin, leftMargin*4/3, leftMargin*4/3)), radius, radius); } // draw app icon const int iconLeftMargins = (boundingRect.width() - iconSize.width()) / 2; const int iconTopMargin = qMin(10, int(boundingRect.height() * 0.1)); const QRect iconRect = QRect(boundingRect.topLeft() + QPoint(iconLeftMargins, iconTopMargin), iconSize); painter->drawPixmap(iconRect, index.data(AppsListModel::AppIconRole).value<QPixmap>()); // draw icon if app is auto startup const QPoint autoStartIconPos = iconRect.bottomLeft() - QPoint(0, m_autoStartPixmap.height()); if (index.data(AppsListModel::AppAutoStartRole).toBool()) painter->drawPixmap(autoStartIconPos, m_autoStartPixmap); // draw app name QTextOption appNameOption; appNameOption.setAlignment(Qt::AlignHCenter | Qt::AlignTop); appNameOption.setWrapMode(QTextOption::WordWrap); QFont appNamefont(painter->font()); appNamefont.setPixelSize(fontPixelSize); const QFontMetrics fm(appNamefont); const QRectF appNameRect = itemTextRect(boundingRect, iconRect, drawBlueDot); // const QRectF appNameBoundingRect = fm.boundingRect(appNameRect.toRect(), appNameOption.alignment() | wrapFlag, itemInfo.m_name); const QString appText = holdTextInRect(fm, itemInfo.m_name, appNameRect.toRect()); // const QString appText = appNameBoundingRect.width() > appNameRect.width() || appNameBoundingRect.height() > appNameRect.height() // ? fm.elidedText(itemInfo.m_name, Qt::ElideRight, appNameRect.width(), appNameOption.alignment() | wrapFlag) // : itemInfo.m_name; painter->setFont(appNamefont); painter->setBrush(QBrush(Qt::transparent)); painter->setPen(QColor(0, 0, 0, 80)); painter->drawText(appNameRect.adjusted(0.8, 1, 0.8, 1), appText, appNameOption); painter->drawText(appNameRect.adjusted(-0.8, 1, -0.8, 1), appText, appNameOption); painter->setPen(Qt::white); painter->drawText(appNameRect, appText, appNameOption); // draw blue dot if needed if (drawBlueDot) { const int marginRight = 2; const QRectF textRect = fm.boundingRect(appNameRect.toRect(), Qt::AlignTop | Qt::AlignHCenter | Qt::TextWordWrap, appText); const QPointF blueDotPos = textRect.topLeft() + QPoint(-m_blueDotPixmap.width() - marginRight, (fm.height() - m_blueDotPixmap.height()) / 2); painter->drawPixmap(blueDotPos, m_blueDotPixmap); } }
void GridItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { PlayableItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) ); if ( !item || !index.isValid() ) return; QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); // qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); QRect r = option.rect; r.setHeight( r.width() ); QString top, bottom; if ( !item->album().isNull() ) { top = item->album()->name(); if ( !item->album()->artist().isNull() ) bottom = item->album()->artist()->name(); } else if ( !item->artist().isNull() ) { top = item->artist()->name(); } else if ( !item->query().isNull() ) { top = item->query()->track()->track(); bottom = item->query()->track()->artist(); } else { return; } painter->save(); painter->setRenderHint( QPainter::TextAntialiasing ); if ( !m_covers.contains( index ) ) { if ( !item->album().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Original, false ) ) ); } else if ( !item->artist().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->artist(), r.size(), TomahawkUtils::Original, false ) ) ); } else { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->query(), r.size(), TomahawkUtils::Original, false ) ) ); } NewClosure( m_covers[ index ], SIGNAL( repaintRequest() ), const_cast<GridItemDelegate*>(this), SLOT( doUpdateIndex( QPersistentModelIndex ) ), QPersistentModelIndex( index ) )->setAutoDelete( false ); } QSharedPointer< Tomahawk::PixmapDelegateFader > fader = m_covers[ index ]; if ( fader->size() != r.size() ) fader->setSize( r.size() ); const QPixmap cover = fader->currentPixmap(); qreal opacity = -1.0; qreal pct = -1.0; if ( m_hoverFaders.contains( index ) ) { pct = ( m_hoverFaders[ index ]->currentFrame() / 100.0 ); opacity = 1.0 - pct * 0.70; } else if ( m_hoverIndex == index ) { opacity = 0.3; pct = 1.0; } if ( opacity > -1.0 ) { painter->save(); const int cropIn = pct * ( (qreal)cover.width() * 0.10 ); const QRect crop = cover.rect().adjusted( cropIn, cropIn, -cropIn, -cropIn ); painter->drawPixmap( r, cover.copy( crop ).scaled( r.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation ) ); painter->setOpacity( 1.0 - opacity ); painter->setPen( Qt::transparent ); painter->setBrush( Qt::black ); painter->drawRect( r ); painter->restore(); } else { painter->drawPixmap( r, cover ); } QTextOption to; to.setWrapMode( QTextOption::NoWrap ); QString text; QRect textRect = option.rect.adjusted( 0, r.height() + m_margin / 4, 0, -m_margin / 2 + m_margin / 8 ); bool oneLiner = false; if ( bottom.isEmpty() ) oneLiner = true; painter->setPen( TomahawkStyle::SELECTION_FOREGROUND ); painter->setFont( m_font ); painter->setPen( Qt::black ); painter->setOpacity( 0.8 ); if ( m_showPosition ) { painter->save(); if ( !oneLiner ) { QFont figFont = m_font; figFont.setPixelSize( textRect.height() - m_margin / 8 ); painter->setFont( figFont ); } const QString fig = QString::number( index.row() + 1 ); painter->drawText( textRect, fig, QTextOption( Qt::AlignLeft | Qt::AlignVCenter ) ); textRect.adjust( painter->fontMetrics().boundingRect( textRect, Qt::AlignLeft | Qt::AlignVCenter, fig ).width() + m_margin / 4, 0, 0, 0 ); painter->restore(); } if ( oneLiner ) { // If the user is hovering over an artist rect, draw a background so they knows it's clickable if ( m_hoveringOverArtist == index ) { QFont f = painter->font(); f.setUnderline( true ); painter->setFont( f ); } to.setAlignment( Qt::AlignLeft | Qt::AlignTop ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - m_margin / 4 ); painter->drawText( textRect, text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = painter->fontMetrics().boundingRect( textRect, Qt::AlignLeft | Qt::AlignTop, text ); } else { painter->save(); // If the user is hovering over an album rect, underline the album name if ( m_hoveringOverAlbum == index ) { QFont f = painter->font(); f.setUnderline( true ); painter->setFont( f ); } if ( m_showBuyButtons && !item->query().isNull() ) { textRect.adjust( 0, 0, 0, -40 ); } to.setAlignment( Qt::AlignLeft | Qt::AlignTop ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - m_margin / 4 ); painter->drawText( textRect, text, to ); if ( item->album() ) { // Calculate rect of album on-hover button click area m_albumNameRects[ index ] = painter->fontMetrics().boundingRect( textRect, Qt::AlignLeft | Qt::AlignTop, text ); } painter->restore(); painter->save(); painter->setOpacity( 0.6 ); painter->setFont( m_smallFont ); // If the user is hovering over an artist rect, underline the artist name if ( m_hoveringOverArtist == index ) { QFont f = painter->font(); f.setUnderline( true ); painter->setFont( f ); } textRect.adjust( 0, painter->fontMetrics().height() + m_margin / 16, 0, 0 ); to.setAlignment( Qt::AlignLeft | Qt::AlignBottom ); text = painter->fontMetrics().elidedText( bottom, Qt::ElideRight, textRect.width() - m_margin / 4 ); painter->drawText( textRect, text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = painter->fontMetrics().boundingRect( textRect, Qt::AlignLeft | Qt::AlignBottom, text ); painter->restore(); if ( m_showBuyButtons && !item->query().isNull() ) { QRect r = textRect; r.setY( textRect.y() + textRect.height() + 8 ); r.setHeight( 32 ); m_buyButtonRects[ index ] = r; QString text; bool itemsAvailable = false; if ( item->result() && ( ( !item->result()->downloadFormats().isEmpty() && !DownloadManager::instance()->localFileForDownload( item->result()->downloadFormats().first().url.toString() ).isEmpty() ) || ( item->result()->downloadJob() && item->result()->downloadJob()->state() == DownloadJob::Finished ) ) ) { text = tr( "View in Finder" ); } else if ( item->query() && item->query()->numResults( true ) && !item->query()->results().first()->downloadFormats().isEmpty() ) { text = tr( "Download %1" ).arg( item->query()->results().first()->downloadFormats().first().extension.toUpper() ); itemsAvailable = true; } else if ( item->query()->numResults( true ) && !item->query()->results().first()->purchaseUrl().isEmpty() ) { text = tr( "Buy" ); } if ( !item->result() || !item->result()->downloadJob() || item->result()->downloadJob()->state() == DownloadJob::Finished ) { if ( !text.isEmpty() ) DropDownButton::drawPrimitive( painter, r, text, m_hoveringOverBuyButton == index, itemsAvailable ); else m_buyButtonRects.remove( index ); } else { painter->setPen( TomahawkStyle::PLAYLIST_PROGRESS_FOREGROUND.darker() ); painter->setBrush( TomahawkStyle::PLAYLIST_PROGRESS_BACKGROUND ); painter->drawRect( r.adjusted( 2, 2, -2, -2 ) ); painter->setPen( TomahawkStyle::PLAYLIST_PROGRESS_FOREGROUND ); painter->setBrush( TomahawkStyle::PLAYLIST_PROGRESS_FOREGROUND ); QRect fillp = r.adjusted( 3, 3, -3, -3 ); fillp.setWidth( float(fillp.width()) * ( float(item->result()->downloadJob()->progressPercentage()) / 100.0 ) ); painter->drawRect( fillp ); } } } painter->restore(); }
void paintContact(QPainter* mp, const QStyleOptionViewItem& option, const QModelIndex& index, GCUserViewItem* item) const { mp->save(); QStyleOptionViewItem o = option; QPalette palette = o.palette; MUCItem::Role r = item->s.mucItem().role(); QRect rect = o.rect; if(nickColoring_) { if(r == MUCItem::Moderator) palette.setColor(QPalette::Text, colorModerator_); else if(r == MUCItem::Participant) palette.setColor(QPalette::Text, colorParticipant_); else if(r == MUCItem::Visitor) palette.setColor(QPalette::Text, colorVisitor_); else palette.setColor(QPalette::Text, colorNoRole_); } mp->fillRect(rect, (o.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base)); if(showAvatar_) { QPixmap ava = item->avatar(); if(ava.isNull()) { ava = IconsetFactory::iconPixmap("psi/default_avatar"); } ava = AvatarFactory::roundedAvatar(ava, avatarRadius_, avatarSize_); QRect avaRect(rect); avaRect.setWidth(ava.width()); avaRect.setHeight(ava.height()); if(!avatarAtLeft_) { avaRect.moveTopRight(rect.topRight()); avaRect.translate(-1, 1); rect.setRight(avaRect.left() - 1); } else { avaRect.translate(1, 1); rect.setLeft(avaRect.right() + 1); } mp->drawPixmap(avaRect, ava); } QPixmap status = showStatusIcons_ ? item->icon() : QPixmap(); int h = rect.height(); int sh = status.isNull() ? 0 : status.height(); rect.setHeight(qMax(sh, fontHeight_)); rect.moveTop(rect.top() + (h - rect.height())/2); if(!status.isNull()) { QRect statusRect(rect); statusRect.setWidth(status.width()); statusRect.setHeight(status.height()); statusRect.translate(1, 1); mp->drawPixmap(statusRect, status); rect.setLeft(statusRect.right() + 2); } else rect.setLeft(rect.left() + 2); mp->setPen(QPen((o.state & QStyle::State_Selected) ? palette.color(QPalette::HighlightedText) : palette.color(QPalette::Text))); mp->setFont(o.font); mp->setClipRect(rect); QTextOption to; to.setWrapMode(QTextOption::NoWrap); mp->drawText(rect, index.data(Qt::DisplayRole).toString(), to); QList<QPixmap> rightPixs; if(showAffiliations_) { MUCItem::Affiliation a = item->s.mucItem().affiliation(); QPixmap pix; if(a == MUCItem::Owner) pix = IconsetFactory::iconPixmap("affiliation/owner"); else if(a == MUCItem::Admin) pix = IconsetFactory::iconPixmap("affiliation/admin"); else if(a == MUCItem::Member) pix = IconsetFactory::iconPixmap("affiliation/member"); else if(a == MUCItem::Outcast) pix = IconsetFactory::iconPixmap("affiliation/outcast"); else pix = IconsetFactory::iconPixmap("affiliation/noaffiliation"); if(!pix.isNull()) rightPixs.push_back(pix); } if(showClients_) { GCUserView *gcuv = (GCUserView*)item->treeWidget(); GCMainDlg* dlg = gcuv->mainDlg(); QPixmap clientPix; if(dlg) { UserListItem u; const QString &nick = item->text(0); Jid caps_jid(/*s.mucItem().jid().isEmpty() ? */ dlg->jid().withResource(nick) /* : s.mucItem().jid()*/); CapsManager *cm = dlg->account()->client()->capsManager(); QString client_name = cm->clientName(caps_jid); QString client_version = (client_name.isEmpty() ? QString() : cm->clientVersion(caps_jid)); UserResource ur; ur.setStatus(item->s); ur.setClient(client_name,client_version,""); u.userResourceList().append(ur); QStringList clients = u.clients(); if(!clients.isEmpty()) clientPix = IconsetFactory::iconPixmap("clients/" + clients.takeFirst()); } if(!clientPix.isNull()) rightPixs.push_back(clientPix); } mp->restore(); if(rightPixs.isEmpty()) return; int sumWidth = 0; foreach (const QPixmap& pix, rightPixs) { sumWidth += pix.width(); } sumWidth += rightPixs.count(); QColor bgc = (option.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base); QColor tbgc = bgc; tbgc.setAlpha(0); QLinearGradient grad(rect.right() - sumWidth - 20, 0, rect.right() - sumWidth, 0); grad.setColorAt(0, tbgc); grad.setColorAt(1, bgc); QBrush tbakBr(grad); QRect gradRect(rect); gradRect.setLeft(gradRect.right() - sumWidth - 20); mp->fillRect(gradRect, tbakBr); QRect iconRect(rect); for (int i=0; i<rightPixs.size(); i++) { const QPixmap pix = rightPixs[i]; iconRect.setRight(iconRect.right() - pix.width() -1); mp->drawPixmap(iconRect.topRight(), pix); } }
void GridItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { PlayableItem* 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 ); QRect r = option.rect; QString top, bottom; if ( !item->album().isNull() ) { top = item->album()->name(); if ( !item->album()->artist().isNull() ) bottom = item->album()->artist()->name(); } else if ( !item->artist().isNull() ) { top = item->artist()->name(); } else { top = item->query()->track(); bottom = item->query()->artist(); } if ( !m_covers.contains( index ) ) { if ( !item->album().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Grid ) ) ); } else if ( !item->artist().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->artist(), r.size(), TomahawkUtils::Grid ) ) ); } else { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->query(), r.size(), TomahawkUtils::Grid ) ) ); } NewClosure( m_covers[ index ], SIGNAL( repaintRequest() ), const_cast<GridItemDelegate*>(this), SLOT( doUpdateIndex( QPersistentModelIndex ) ), QPersistentModelIndex( index ) )->setAutoDelete( false ); } QSharedPointer< Tomahawk::PixmapDelegateFader > fader = m_covers[ index ]; if ( fader->size() != r.size() ) fader->setSize( r.size() ); const QPixmap cover = fader->currentPixmap(); painter->drawPixmap( r, cover ); qreal opacity = -1.; if ( m_hoverFaders.contains( index ) ) { const qreal pct = ( m_hoverFaders[ index ]->currentFrame() / 100. ); opacity = 0.35 - pct * 0.35; } else if ( m_hoverIndex == index ) { opacity = 0.35; } if ( opacity > -1. ) { painter->save(); painter->setPen( QColor( 33, 33, 33 ) ); painter->setBrush( QColor( 33, 33, 33 ) ); painter->setOpacity( opacity ); painter->drawRect( r ); painter->restore(); } painter->save(); painter->setPen( Qt::black ); painter->setBrush( Qt::black ); painter->setOpacity( 0.5 ); painter->drawRoundedRect( r.adjusted( 4, +r.height() - 36, -4, -4 ), 3, 3 ); painter->restore(); painter->setPen( opt.palette.color( QPalette::HighlightedText ) ); QTextOption to; to.setWrapMode( QTextOption::NoWrap ); QString text; QFont font = opt.font; font.setPointSize( TomahawkUtils::defaultFontSize() ); QFont boldFont = font; boldFont.setBold( true ); boldFont.setPointSize( TomahawkUtils::defaultFontSize() + 1 ); QRect textRect = option.rect.adjusted( 6, option.rect.height() - 36, -4, -6 ); painter->setFont( font ); int bottomHeight = painter->fontMetrics().boundingRect( bottom ).height(); painter->setFont( boldFont ); int topHeight = painter->fontMetrics().boundingRect( top ).height(); bool oneLiner = false; if ( bottom.isEmpty() ) oneLiner = true; else oneLiner = ( textRect.height() < topHeight + bottomHeight ); if ( oneLiner ) { to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); } else { to.setAlignment( Qt::AlignHCenter | Qt::AlignTop ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); painter->setFont( font ); // 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.1 ); painter->setPen( opt.palette.color( QPalette::HighlightedText ) ); } to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom ); text = painter->fontMetrics().elidedText( bottom, Qt::ElideRight, textRect.width() - 10 ); painter->drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = r; } painter->restore(); }
void QSvgText::draw(QPainter *p, QSvgExtraStates &states) { applyStyle(p, states); qreal oldOpacity = p->opacity(); p->setOpacity(oldOpacity * states.fillOpacity); // Force the font to have a size of 100 pixels to avoid truncation problems // when the font is very small. qreal scale = 100.0 / p->font().pointSizeF(); Qt::Alignment alignment = states.textAnchor; QTransform oldTransform = p->worldTransform(); p->scale(1 / scale, 1 / scale); qreal y = 0; bool initial = true; qreal px = m_coord.x() * scale; qreal py = m_coord.y() * scale; QSizeF scaledSize = m_size * scale; if (m_type == TEXTAREA) { if (alignment == Qt::AlignHCenter) px += scaledSize.width() / 2; else if (alignment == Qt::AlignRight) px += scaledSize.width(); } QRectF bounds; if (m_size.height() != 0) bounds = QRectF(0, py, 1, scaledSize.height()); // x and width are not used. bool appendSpace = false; QVector<QString> paragraphs; QStack<QTextCharFormat> formats; QVector<QList<QTextLayout::FormatRange> > formatRanges; paragraphs.push_back(QString()); formatRanges.push_back(QList<QTextLayout::FormatRange>()); for (int i = 0; i < m_tspans.size(); ++i) { if (m_tspans[i] == LINEBREAK) { if (m_type == TEXTAREA) { if (paragraphs.back().isEmpty()) { QFont font = p->font(); font.setPixelSize(font.pointSizeF() * scale); QTextLayout::FormatRange range; range.start = 0; range.length = 1; range.format.setFont(font); formatRanges.back().append(range); paragraphs.back().append(QLatin1Char(' '));; } appendSpace = false; paragraphs.push_back(QString()); formatRanges.push_back(QList<QTextLayout::FormatRange>()); } } else { WhitespaceMode mode = m_tspans[i]->whitespaceMode(); m_tspans[i]->applyStyle(p, states); QFont font = p->font(); font.setPixelSize(font.pointSizeF() * scale); QString newText(m_tspans[i]->text()); newText.replace(QLatin1Char('\t'), QLatin1Char(' ')); newText.replace(QLatin1Char('\n'), QLatin1Char(' ')); bool prependSpace = !appendSpace && !m_tspans[i]->isTspan() && (mode == Default) && !paragraphs.back().isEmpty() && newText.startsWith(QLatin1Char(' ')); if (appendSpace || prependSpace) paragraphs.back().append(QLatin1Char(' ')); bool appendSpaceNext = (!m_tspans[i]->isTspan() && (mode == Default) && newText.endsWith(QLatin1Char(' '))); if (mode == Default) { newText = newText.simplified(); if (newText.isEmpty()) appendSpaceNext = false; } QTextLayout::FormatRange range; range.start = paragraphs.back().length(); range.length = newText.length(); range.format.setFont(font); range.format.setTextOutline(p->pen()); range.format.setForeground(p->brush()); if (appendSpace) { Q_ASSERT(!formatRanges.back().isEmpty()); ++formatRanges.back().back().length; } else if (prependSpace) { --range.start; ++range.length; } formatRanges.back().append(range); appendSpace = appendSpaceNext; paragraphs.back() += newText; m_tspans[i]->revertStyle(p, states); } } if (states.svgFont) { // SVG fonts not fully supported... QString text = paragraphs.front(); for (int i = 1; i < paragraphs.size(); ++i) { text.append(QLatin1Char('\n')); text.append(paragraphs[i]); } states.svgFont->draw(p, m_coord * scale, text, p->font().pointSizeF() * scale, states.textAnchor); } else { for (int i = 0; i < paragraphs.size(); ++i) { QTextLayout tl(paragraphs[i]); QTextOption op = tl.textOption(); op.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); tl.setTextOption(op); tl.setAdditionalFormats(formatRanges[i]); tl.beginLayout(); forever { QTextLine line = tl.createLine(); if (!line.isValid()) break; if (m_size.width() != 0) line.setLineWidth(scaledSize.width()); } tl.endLayout(); bool endOfBoundsReached = false; for (int i = 0; i < tl.lineCount(); ++i) { QTextLine line = tl.lineAt(i); qreal x = 0; if (alignment == Qt::AlignHCenter) x -= 0.5 * line.naturalTextWidth(); else if (alignment == Qt::AlignRight) x -= line.naturalTextWidth(); if (initial && m_type == TEXT) y -= line.ascent(); initial = false; line.setPosition(QPointF(x, y)); // Check if the current line fits into the bounding rectangle. if ((m_size.width() != 0 && line.naturalTextWidth() > scaledSize.width()) || (m_size.height() != 0 && y + line.height() > scaledSize.height())) { // I need to set the bounds height to 'y-epsilon' to avoid drawing the current // line. Since the font is scaled to 100 units, 1 should be a safe epsilon. bounds.setHeight(y - 1); endOfBoundsReached = true; break; } y += 1.1 * line.height(); } tl.draw(p, QPointF(px, py), QVector<QTextLayout::FormatRange>(), bounds); if (endOfBoundsReached) break; } } p->setWorldTransform(oldTransform, false); p->setOpacity(oldOpacity); revertStyle(p, states); }
SimpleRichTextEdit::SimpleRichTextEdit(QWidget *parent) : KTextEdit(parent) { enableFindReplace(false); setCheckSpellingEnabled(true); setAutoFormatting(KTextEdit::AutoNone); setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); QTextDocument *textDocument = document(); QTextOption textOption; textOption.setAlignment(Qt::AlignCenter); textOption.setWrapMode(QTextOption::NoWrap); textDocument->setDefaultTextOption(textOption); QFont defaultFont = font(); defaultFont.setPointSize(defaultFont.pointSize() + 2); textDocument->setDefaultFont(defaultFont); QString styleSheet("p {" " display: block;" " white-space: pre;" " margin-top: 0px;" " margin-bottom: 0px;" "}"); textDocument->setDefaultStyleSheet(styleSheet); setTextInteractionFlags(Qt::TextEditorInteraction); m_actions[Undo] = new QAction(this); m_actions[Undo]->setIcon(QIcon::fromTheme("edit-undo")); m_actions[Undo]->setText(i18n("Undo")); m_actions[Undo]->setShortcuts(KStandardShortcut::undo()); connect(m_actions[Undo], SIGNAL(triggered()), this, SLOT(undo())); m_actions[Redo] = new QAction(this); m_actions[Redo]->setIcon(QIcon::fromTheme("edit-redo")); m_actions[Redo]->setText(i18n("Redo")); m_actions[Redo]->setShortcuts(KStandardShortcut::redo()); connect(m_actions[Redo], SIGNAL(triggered()), this, SLOT(redo())); m_actions[Cut] = new QAction(this); m_actions[Cut]->setIcon(QIcon::fromTheme("edit-cut")); m_actions[Cut]->setText(i18n("Cut")); m_actions[Cut]->setShortcuts(KStandardShortcut::cut()); connect(m_actions[Cut], SIGNAL(triggered()), this, SLOT(cut())); m_actions[Copy] = new QAction(this); m_actions[Copy]->setIcon(QIcon::fromTheme("edit-copy")); m_actions[Copy]->setText(i18n("Copy")); m_actions[Copy]->setShortcuts(KStandardShortcut::copy()); connect(m_actions[Copy], SIGNAL(triggered()), this, SLOT(copy())); #if !defined(QT_NO_CLIPBOARD) m_actions[Paste] = new QAction(this); m_actions[Paste]->setIcon(QIcon::fromTheme("edit-paste")); m_actions[Paste]->setText(i18n("Paste")); m_actions[Paste]->setShortcuts(KStandardShortcut::paste()); connect(m_actions[Paste], SIGNAL(triggered()), this, SLOT(paste())); #endif m_actions[Delete] = new QAction(this); m_actions[Delete]->setIcon(QIcon::fromTheme("edit-delete")); m_actions[Delete]->setText(i18n("Delete")); m_actions[Delete]->setShortcut(QKeySequence::Delete); connect(m_actions[Delete], SIGNAL(triggered()), this, SLOT(deleteText())); m_actions[Clear] = new QAction(this); m_actions[Clear]->setIcon(QIcon::fromTheme("edit-clear")); m_actions[Clear]->setText(i18nc("@action:inmenu Clear all text", "Clear")); connect(m_actions[Clear], SIGNAL(triggered()), this, SLOT(undoableClear())); m_actions[SelectAll] = new QAction(this); m_actions[SelectAll]->setIcon(QIcon::fromTheme("edit-select-all")); m_actions[SelectAll]->setText(i18n("Select All")); m_actions[SelectAll]->setShortcut(QKeySequence::SelectAll); connect(m_actions[SelectAll], SIGNAL(triggered()), this, SLOT(selectAll())); m_actions[ToggleBold] = new QAction(this); m_actions[ToggleBold]->setIcon(QIcon::fromTheme("format-text-bold")); m_actions[ToggleBold]->setText(i18nc("@action:inmenu Toggle bold style", "Bold")); m_actions[ToggleBold]->setShortcut(QKeySequence("Ctrl+B")); connect(m_actions[ToggleBold], SIGNAL(triggered()), this, SLOT(toggleFontBold())); m_actions[ToggleItalic] = new QAction(this); m_actions[ToggleItalic]->setIcon(QIcon::fromTheme("format-text-italic")); m_actions[ToggleItalic]->setText(i18nc("@action:inmenu Toggle italic style", "Italic")); m_actions[ToggleItalic]->setShortcut(QKeySequence("Ctrl+I")); connect(m_actions[ToggleItalic], SIGNAL(triggered()), this, SLOT(toggleFontItalic())); m_actions[ToggleUnderline] = new QAction(this); m_actions[ToggleUnderline]->setIcon(QIcon::fromTheme("format-text-underline")); m_actions[ToggleUnderline]->setText(i18nc("@action:inmenu Toggle underline style", "Underline")); m_actions[ToggleUnderline]->setShortcut(QKeySequence("Ctrl+U")); connect(m_actions[ToggleUnderline], SIGNAL(triggered()), this, SLOT(toggleFontUnderline())); m_actions[ToggleStrikeOut] = new QAction(this); m_actions[ToggleStrikeOut]->setIcon(QIcon::fromTheme("format-text-strikethrough")); m_actions[ToggleStrikeOut]->setText(i18nc("@action:inmenu Toggle strike through style", "Strike Through")); m_actions[ToggleStrikeOut]->setShortcut(QKeySequence("Ctrl+T")); connect(m_actions[ToggleStrikeOut], SIGNAL(triggered()), this, SLOT(toggleFontStrikeOut())); m_actions[ChangeTextColor] = new QAction(this); m_actions[ChangeTextColor]->setIcon(QIcon::fromTheme("format-text-color")); m_actions[ChangeTextColor]->setText(i18nc("@action:inmenu Change Text Color", "Text Color")); m_actions[ChangeTextColor]->setShortcut(QKeySequence("Ctrl+Shift+C")); connect(m_actions[ChangeTextColor], SIGNAL(triggered()), this, SLOT(changeTextColor())); m_actions[CheckSpelling] = new QAction(this); m_actions[CheckSpelling]->setIcon(QIcon::fromTheme("tools-check-spelling")); m_actions[CheckSpelling]->setText(i18n("Check Spelling...")); connect(m_actions[CheckSpelling], SIGNAL(triggered()), this, SLOT(checkSpelling())); m_actions[ToggleAutoSpellChecking] = new QAction(this); m_actions[ToggleAutoSpellChecking]->setText(i18n("Auto Spell Check")); m_actions[ToggleAutoSpellChecking]->setCheckable(true); connect(m_actions[ToggleAutoSpellChecking], SIGNAL(triggered()), this, SLOT(toggleAutoSpellChecking())); m_actions[AllowTabulations] = new QAction(this); m_actions[AllowTabulations]->setText(i18n("Allow Tabulations")); connect(m_actions[AllowTabulations], SIGNAL(triggered()), this, SLOT(toggleTabChangesFocus())); QMenu *menu = createStandardContextMenu(); menu->setParent(this); QList<QAction *> actions = menu->actions(); m_insertUnicodeControlCharMenu = 0; for(QList<QAction *>::ConstIterator it = actions.constBegin(), end = actions.constEnd(); it != end; ++it) { if((*it)->menu()) { // this depends on Qt private implementation but at least is guaranteed // to behave reasonably if that implementation changes in the future. if(!strcmp((*it)->menu()->metaObject()->className(), "QUnicodeControlCharacterMenu")) { m_insertUnicodeControlCharMenu = (*it)->menu(); break; } } } }
// FIXME: we need to figure out a way to derive from Fm::FolderItemDelegate to avoid code duplication. void DesktopItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { Q_ASSERT(index.isValid()); QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); painter->save(); painter->setClipRect(option.rect); opt.decorationAlignment = Qt::AlignHCenter | Qt::AlignTop; opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; // draw the icon QIcon::Mode iconMode; if(opt.state & QStyle::State_Enabled) { if(opt.state & QStyle::State_Selected) iconMode = QIcon::Selected; else { iconMode = QIcon::Normal; } } else iconMode = QIcon::Disabled; QPoint iconPos(opt.rect.x() + (opt.rect.width() - opt.decorationSize.width()) / 2, opt.rect.y()); QPixmap pixmap = opt.icon.pixmap(opt.decorationSize, iconMode); painter->drawPixmap(iconPos, pixmap); // draw some emblems for the item if needed // we only support symlink emblem at the moment FmFileInfo* file = static_cast<FmFileInfo*>(index.data(Fm::FolderModel::FileInfoRole).value<void*>()); if(file) { if(fm_file_info_is_symlink(file)) { painter->drawPixmap(iconPos, symlinkIcon_.pixmap(opt.decorationSize / 2, iconMode)); } } // draw text QRectF textRect(opt.rect.x(), opt.rect.y() + opt.decorationSize.height(), opt.rect.width(), opt.rect.height() - opt.decorationSize.height()); QTextLayout layout(opt.text, opt.font); QTextOption textOption; textOption.setAlignment(opt.displayAlignment); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); textOption.setTextDirection(opt.direction); layout.setTextOption(textOption); qreal height = 0; qreal width = 0; int visibleLines = 0; layout.beginLayout(); QString elidedText; for(;;) { QTextLine line = layout.createLine(); if(!line.isValid()) break; line.setLineWidth(textRect.width()); height += opt.fontMetrics.leading(); line.setPosition(QPointF(0, height)); if((height + line.height() + textRect.y()) > textRect.bottom()) { // if part of this line falls outside the textRect, ignore it and quit. QTextLine lastLine = layout.lineAt(visibleLines - 1); elidedText = opt.text.mid(lastLine.textStart()); elidedText = opt.fontMetrics.elidedText(elidedText, opt.textElideMode, textRect.width()); break; } height += line.height(); width = qMax(width, line.naturalTextWidth()); ++ visibleLines; } layout.endLayout(); QRectF boundRect = layout.boundingRect(); boundRect.setWidth(width); boundRect.moveTo(textRect.x() + (textRect.width() - width)/2, textRect.y()); if((opt.state & QStyle::State_Selected) && opt.widget) { QPalette palette = opt.widget->palette(); // qDebug("w: %f, h:%f, m:%f", boundRect.width(), boundRect.height(), layout.minimumWidth()); painter->fillRect(boundRect, palette.highlight()); } else { // only draw shadow for non-selected items // draw shadow, FIXME: is it possible to use QGraphicsDropShadowEffect here? QPen prevPen = painter->pen(); painter->setPen(QPen(shadowColor_)); for(int i = 0; i < visibleLines; ++i) { QTextLine line = layout.lineAt(i); if(i == (visibleLines - 1) && !elidedText.isEmpty()) { // the last line, draw elided text QPointF pos(textRect.x() + line.position().x() + 1, textRect.y() + line.y() + line.ascent() + 1); painter->drawText(pos, elidedText); } else { line.draw(painter, textRect.topLeft() + QPointF(1, 1)); } } painter->setPen(prevPen); } // draw text for(int i = 0; i < visibleLines; ++i) { QTextLine line = layout.lineAt(i); if(i == (visibleLines - 1) && !elidedText.isEmpty()) { // the last line, draw elided text QPointF pos(textRect.x() + line.position().x(), textRect.y() + line.y() + line.ascent()); painter->drawText(pos, elidedText); } else { line.draw(painter, textRect.topLeft()); } } if(opt.state & QStyle::State_HasFocus) { // FIXME: draw focus rect } painter->restore(); }
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; if ( !item->album().isNull() ) { cover.loadFromData( item->album()->cover() ); } else if ( !item->artist().isNull() ) { cover.loadFromData( item->artist()->cover() ); } if ( cover.isNull() ) cover = m_defaultCover; 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.1 ); painter->setPen( opt.palette.color( QPalette::HighlightedText ) ); } else { if ( !( option.state & QStyle::State_Selected ) ) #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() - 10 ); painter->drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = r; } painter->restore(); }
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 ) ); }*/ // QRect r = option.rect.adjusted( 6, 5, -6, -41 ); QRect r = option.rect; QString top, bottom; if ( !item->album().isNull() ) { top = item->album()->name(); if ( !item->album()->artist().isNull() ) bottom = item->album()->artist()->name(); } else if ( !item->artist().isNull() ) { top = item->artist()->name(); } else { top = item->query()->track(); bottom = item->query()->artist(); } if ( !m_covers.contains( index ) ) { if ( !item->album().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Grid ) ) ); } else if ( !item->artist().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->artist(), r.size(), TomahawkUtils::Grid ) ) ); } else { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->query(), r.size(), TomahawkUtils::Grid ) ) ); } _detail::Closure* closure = NewClosure( m_covers[ index ], SIGNAL( repaintRequest() ), const_cast<AlbumItemDelegate*>(this), SLOT( doUpdateIndex( QPersistentModelIndex ) ), QPersistentModelIndex( index ) ); closure->setAutoDelete( false ); } const QPixmap cover = m_covers[ index ]->currentPixmap(); if ( false && option.state & QStyle::State_Selected ) { #if defined(Q_WS_MAC) || defined(Q_WS_WIN) painter->save(); 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 } painter->drawPixmap( r, cover.scaled( r.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation ) ); if ( m_hoverIndex == index ) { painter->save(); painter->setPen( QColor( 33, 33, 33 ) ); painter->setBrush( QColor( 33, 33, 33 ) ); painter->setOpacity( 0.5 ); painter->drawRect( r ); painter->restore(); } painter->save(); painter->setPen( QColor( 33, 33, 33 ) ); painter->setBrush( QColor( 33, 33, 33 ) ); painter->setOpacity( 0.5 ); painter->drawRoundedRect( r.adjusted( 4, +r.height() - 36, -4, -4 ), 3, 3 ); painter->restore(); painter->setPen( opt.palette.color( QPalette::HighlightedText ) ); QTextOption to; to.setWrapMode( QTextOption::NoWrap ); QString text; QFont font = opt.font; font.setPixelSize( 10 ); QFont boldFont = font; boldFont.setBold( true ); boldFont.setPixelSize( 14 ); QRect textRect = option.rect.adjusted( 6, option.rect.height() - 36, -4, -6 ); painter->setFont( boldFont ); bool oneLiner = false; if ( bottom.isEmpty() ) oneLiner = true; else oneLiner = ( textRect.height() / 2 < painter->fontMetrics().boundingRect( top ).height() || textRect.height() / 2 < painter->fontMetrics().boundingRect( bottom ).height() ); if ( oneLiner ) { to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); } else { to.setAlignment( Qt::AlignHCenter | Qt::AlignTop ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); painter->setFont( font ); // 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.1 ); painter->setPen( opt.palette.color( QPalette::HighlightedText ) ); } else { /* if ( !( option.state & QStyle::State_Selected ) ) #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( bottom, Qt::ElideRight, textRect.width() - 10 ); painter->drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = r; } painter->restore(); }