QSize QwtRichTextEngine::textSize(const QFont &font, int flags, const QString& text) const { QwtRichTextDocument doc(text, flags, font); #if QT_VERSION < 0x040000 doc.setWidth(QWIDGETSIZE_MAX); const int w = doc.widthUsed(); const int h = doc.height(); return QSize(w, h); #else // QT_VERSION >= 0x040000 #if QT_VERSION < 0x040200 /* Unfortunately offering the bounding rect calculation in the API of QTextDocument has been forgotten in Qt <= 4.1.x. It is planned to come with Qt 4.2.x. In the meantime we need a hack with a temporary QLabel, to reengineer the internal calculations. */ static int off = 0; static QLabel *label = NULL; if ( label == NULL ) { label = new QLabel; label->hide(); const char *s = "XXXXX"; label->setText(s); int w1 = label->sizeHint().width(); const QFontMetrics fm(label->font()); int w2 = fm.width(s); off = w1 - w2; } label->setFont(doc.defaultFont()); label->setText(text); int w = qwtMax(label->sizeHint().width() - off, 0); doc.setPageSize(QSize(w, QWIDGETSIZE_MAX)); int h = qRound(doc.documentLayout()->documentSize().height()); return QSize(w, h); #else // QT_VERSION >= 0x040200 #if QT_VERSION >= 0x040300 QTextOption option = doc.defaultTextOption(); if ( option.wrapMode() != QTextOption::NoWrap ) { option.setWrapMode(QTextOption::NoWrap); doc.setDefaultTextOption(option); doc.adjustSize(); } #endif return doc.size().toSize(); #endif #endif }
// 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(); }
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; } } } }
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); }
void PlaylistDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); if ( option.state & QStyle::State_Selected && option.state & QStyle::State_Active ) { opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) ); } painter->save(); painter->setRenderHint( QPainter::Antialiasing ); painter->setPen( opt.palette.color( QPalette::Text ) ); QTextOption to; to.setAlignment( Qt::AlignCenter ); QFont font = opt.font; font.setPointSize( TomahawkUtils::defaultFontSize() - 1 ); QFont boldFont = font; boldFont.setBold( true ); boldFont.setPointSize( TomahawkUtils::defaultFontSize() ); QFontMetrics boldFontMetrics( boldFont ); QFont figFont = boldFont; figFont.setPointSize( TomahawkUtils::defaultFontSize() - 1 ); QPixmap icon; QRect pixmapRect = option.rect.adjusted( 10, 14, -option.rect.width() + option.rect.height() - 18, -14 ); RecentlyPlayedPlaylistsModel::PlaylistTypes type = (RecentlyPlayedPlaylistsModel::PlaylistTypes)index.data( RecentlyPlayedPlaylistsModel::PlaylistTypeRole ).toInt(); if ( type == RecentlyPlayedPlaylistsModel::StaticPlaylist ) icon = TomahawkUtils::defaultPixmap( TomahawkUtils::Playlist, TomahawkUtils::Original, pixmapRect.size() ); else if ( type == RecentlyPlayedPlaylistsModel::AutoPlaylist ) icon = TomahawkUtils::defaultPixmap( TomahawkUtils::AutomaticPlaylist, TomahawkUtils::Original, pixmapRect.size() ); else if ( type == RecentlyPlayedPlaylistsModel::Station ) icon = TomahawkUtils::defaultPixmap( TomahawkUtils::Station, TomahawkUtils::Original, pixmapRect.size() ); painter->drawPixmap( pixmapRect, icon ); if ( type != RecentlyPlayedPlaylistsModel::Station ) { painter->save(); painter->setFont( figFont ); QString tracks = index.data( RecentlyPlayedPlaylistsModel::TrackCountRole ).toString(); int width = painter->fontMetrics().width( tracks ); // int bottomEdge = pixmapRect // right edge 10px past right edge of pixmapRect // bottom edge flush with bottom of pixmap QRect rect( pixmapRect.right() - width, 0, width - 8, 0 ); rect.adjust( -2, 0, 0, 0 ); rect.setTop( pixmapRect.bottom() - painter->fontMetrics().height() - 1 ); rect.setBottom( pixmapRect.bottom() + 1 ); QColor figColor( TomahawkStyle::DASHBOARD_ROUNDFIGURE_BACKGROUND ); painter->setPen( Qt::white ); painter->setBrush( figColor ); TomahawkUtils::drawBackgroundAndNumbers( painter, tracks, rect ); painter->restore(); } QRect r( option.rect.width() - option.fontMetrics.height() * 2.5 - 10, option.rect.top() + option.rect.height() / 3 - option.fontMetrics.height(), option.fontMetrics.height() * 2.5, option.fontMetrics.height() * 2.5 ); QPixmap avatar = index.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >()->author()->avatar( TomahawkUtils::RoundedCorners, r.size() ); if ( avatar.isNull() ) avatar = TomahawkUtils::defaultPixmap( TomahawkUtils::DefaultSourceAvatar, TomahawkUtils::RoundedCorners, r.size() ); painter->drawPixmap( r, avatar ); painter->setFont( font ); QString author = index.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >()->author()->friendlyName(); if ( author.indexOf( '@' ) > 0 ) author = author.mid( 0, author.indexOf( '@' ) ); const int w = painter->fontMetrics().width( author ) + 2; QRect avatarNameRect( opt.rect.width() - 10 - w, r.bottom(), w, opt.rect.bottom() - r.bottom() ); painter->drawText( avatarNameRect, author, QTextOption( Qt::AlignCenter ) ); const int leftEdge = opt.rect.width() - qMin( avatarNameRect.left(), r.left() ); QString descText; if ( type == RecentlyPlayedPlaylistsModel::Station ) { descText = index.data( RecentlyPlayedPlaylistsModel::DynamicPlaylistRole ).value< Tomahawk::dynplaylist_ptr >()->generator()->sentenceSummary(); } else { descText = index.data( RecentlyPlayedPlaylistsModel::ArtistRole ).toString(); } QColor c = painter->pen().color(); if ( !( option.state & QStyle::State_Selected && option.state & QStyle::State_Active ) ) { painter->setPen( opt.palette.text().color().darker() ); } QRect rectText = option.rect.adjusted( option.fontMetrics.height() * 4.5, boldFontMetrics.height() + 6, -leftEdge - 10, -8 ); #ifdef Q_WS_MAC rectText.adjust( 0, 1, 0, 0 ); #elif defined Q_WS_WIN rectText.adjust( 0, 2, 0, 0 ); #endif painter->drawText( rectText, descText ); painter->setPen( c ); painter->setFont( font ); painter->setFont( boldFont ); painter->drawText( option.rect.adjusted( option.fontMetrics.height() * 4, 6, -100, -option.rect.height() + boldFontMetrics.height() + 6 ), index.data().toString() ); painter->restore(); }
void KStandardItemListWidget::updateIconsLayoutTextCache() { // +------+ // | Icon | // +------+ // // Name role that // might get wrapped above // several lines. // Additional role 1 // Additional role 2 const QHash<QByteArray, QVariant> values = data(); const KItemListStyleOption& option = styleOption(); const qreal padding = option.padding; const qreal maxWidth = size().width() - 2 * padding; const qreal widgetHeight = size().height(); const qreal lineSpacing = m_customizedFontMetrics.lineSpacing(); // Initialize properties for the "text" role. It will be used as anchor // for initializing the position of the other roles. TextInfo* nameTextInfo = m_textInfo.value("text"); const QString nameText = KStringHandler::preProcessWrap(values["text"].toString()); nameTextInfo->staticText.setText(nameText); // Calculate the number of lines required for the name and the required width qreal nameWidth = 0; qreal nameHeight = 0; QTextLine line; const int additionalRolesCount = qMax(visibleRoles().count() - 1, 0); const int maxNameLines = (option.maxTextSize.height() / int(lineSpacing)) - additionalRolesCount; QTextLayout layout(nameTextInfo->staticText.text(), m_customizedFont); layout.setTextOption(nameTextInfo->staticText.textOption()); layout.beginLayout(); int nameLineIndex = 0; while ((line = layout.createLine()).isValid()) { line.setLineWidth(maxWidth); nameWidth = qMax(nameWidth, line.naturalTextWidth()); nameHeight += line.height(); ++nameLineIndex; if (nameLineIndex == maxNameLines) { // The maximum number of textlines has been reached. If this is // the case provide an elided text if necessary. const int textLength = line.textStart() + line.textLength(); if (textLength < nameText.length()) { // Elide the last line of the text QString lastTextLine = nameText.mid(line.textStart(), line.textLength()); lastTextLine = m_customizedFontMetrics.elidedText(lastTextLine, Qt::ElideRight, line.naturalTextWidth() - 1); const QString elidedText = nameText.left(line.textStart()) + lastTextLine; nameTextInfo->staticText.setText(elidedText); } break; } } layout.endLayout(); // Use one line for each additional information nameTextInfo->staticText.setTextWidth(maxWidth); nameTextInfo->pos = QPointF(padding, widgetHeight - nameHeight - additionalRolesCount * lineSpacing - padding); m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2, nameTextInfo->pos.y(), nameWidth, nameHeight); // Calculate the position for each additional information qreal y = nameTextInfo->pos.y() + nameHeight; foreach (const QByteArray& role, m_sortedVisibleRoles) { if (role == "text") { continue; } const QString text = roleText(role, values); TextInfo* textInfo = m_textInfo.value(role); textInfo->staticText.setText(text); qreal requiredWidth = 0; QTextLayout layout(text, m_customizedFont); QTextOption textOption; textOption.setWrapMode(QTextOption::NoWrap); layout.setTextOption(textOption); layout.beginLayout(); QTextLine textLine = layout.createLine(); if (textLine.isValid()) { textLine.setLineWidth(maxWidth); requiredWidth = textLine.naturalTextWidth(); if (requiredWidth > maxWidth) { const QString elidedText = m_customizedFontMetrics.elidedText(text, Qt::ElideRight, maxWidth); textInfo->staticText.setText(elidedText); requiredWidth = m_customizedFontMetrics.width(elidedText); } else if (role == "rating") { // Use the width of the rating pixmap, because the rating text is empty. requiredWidth = m_rating.width(); } } layout.endLayout(); textInfo->pos = QPointF(padding, y); textInfo->staticText.setTextWidth(maxWidth); const QRectF textRect(padding + (maxWidth - requiredWidth) / 2, y, requiredWidth, lineSpacing); m_textRect |= textRect; y += lineSpacing; } // Add a padding to the text rectangle m_textRect.adjust(-padding, -padding, padding, padding); }
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) const { mp->save(); QStyleOptionViewItem o = option; QPalette palette = o.palette; MUCItem::Role r = index.data(GCUserModel::StatusRole).value<Status>().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 = index.data(GCUserModel::AvatarRole).value<QPixmap>(); 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_? PsiIconset::instance()->status(index.data(GCUserModel::StatusRole).value<Status>()).pixmap() : 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_) { QPixmap pix = index.data(GCUserModel::AffilationIconRole).value<QPixmap>();; if(!pix.isNull()) rightPixs.push_back(pix); } if(showClients_) { QPixmap clientPix = index.data(GCUserModel::ClientIconRole).value<QPixmap>(); 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); } }
/** * Set the alignment for the item's text. * * @param align An OR combination specifying the alignment. * * @note The text width of this item should be set by setTextWidth for * center alignment. */ void TextItem::setAlignment(Qt::Alignment align) { QTextOption opt = document()->defaultTextOption(); opt.setAlignment(align); document()->setDefaultTextOption(opt); }
void QSvgText::draw(QPainter *p, QSvgExtraStates &states) { applyStyle(p, states); QSvgFontStyle *fontStyle = static_cast<QSvgFontStyle*>( styleProperty(QSvgStyleProperty::FONT)); if (fontStyle && fontStyle->svgFont()) { // SVG fonts not fully supported... QString text = m_paragraphs.front(); for (int i = 1; i < m_paragraphs.size(); ++i) { text.append(QLatin1Char('\n')); text.append(m_paragraphs[i]); } fontStyle->svgFont()->draw(p, m_coord, text, fontStyle->pointSize(), m_textAlignment); revertStyle(p, states); return; } // Scale the font to its correct size. QTransform oldTransform = p->worldTransform(); p->scale(1 / m_scale, 1 / m_scale); qreal y = 0; bool initial = true; qreal px = m_coord.x() * m_scale; qreal py = m_coord.y() * m_scale; QSizeF scaledSize = m_size * m_scale; if (m_type == TEXTAREA) { if (m_textAlignment == Qt::AlignHCenter) px += scaledSize.width() / 2; else if (m_textAlignment == Qt::AlignRight) px += scaledSize.width(); } QRectF bounds; if (m_size.height() != 0) bounds = QRectF(0, 0, 1, scaledSize.height()); for (int i = 0; i < m_paragraphs.size(); ++i) { QTextLayout tl(m_paragraphs[i]); QTextOption op = tl.textOption(); op.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); tl.setTextOption(op); tl.setAdditionalFormats(m_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 (m_textAlignment == Qt::AlignHCenter) x -= line.naturalTextWidth() / 2; else if (m_textAlignment == Qt::AlignRight) x -= line.naturalTextWidth(); if (initial && m_type == TEXT) y -= line.ascent(); initial = false; line.setPosition(QPointF(x, y)); if ((m_size.width() != 0 && line.naturalTextWidth() > scaledSize.width()) || (m_size.height() != 0 && y + line.height() > scaledSize.height())) { bounds.setHeight(y); 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); revertStyle(p, states); }
void OpenFileItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { Location location = index.data(OpenFileTreeModel::LocationRole).value<Location>(); BaseFile* file = (BaseFile*)index.data(OpenFileTreeModel::FileRole).value<void*>(); OpenFileTreeModel::Level level = (OpenFileTreeModel::Level)index.data(OpenFileTreeModel::TypeRole).toInt(); QString label = index.data(OpenFileTreeModel::LabelRole).toString(); // Always paint the default background QStyledItemDelegate::paint(painter, option, index); if (mParent->closeColumn() && index.column() == mParent->closeColumn()) { // Show the close icon, but it's only visible on mouse-over. QStyledItemDelegate::paint(painter, option, index); if (option.state & QStyle::State_MouseOver) painter->drawPixmap(option.rect.left(), option.rect.top(), 16, 16, QPixmap(":/icons/cross.png")); } else if (mParent->refreshColumn() && index.column() == mParent->refreshColumn()) { // Show the refresh icon, but it's only visible on mouse-over. QStyledItemDelegate::paint(painter, option, index); if (option.state & QStyle::State_MouseOver) painter->drawPixmap(option.rect.left(), option.rect.top(), 16, 16, QPixmap(":/icons/resync.png")); } else { // Column 0 contains the label, and if it's a file also the status. QRect labelRect = option.rect; QPaintDevice* device = painter->device(); painter->end(); { QStylePainter sp(device, mParent); if (level == OpenFileTreeModel::File) { BaseFile::OpenStatus fileStatus = file->getOpenStatus(); if (file->hasUnsavedChanges()) { sp.drawPixmap(labelRect.right() - 16, labelRect.top(), 16, 16, QPixmap(":/icons/filechanged.png")); labelRect.adjust(0, 0, -18, 0); } if (fileStatus == BaseFile::Disconnected || fileStatus == BaseFile::Reconnecting) { sp.drawPixmap(labelRect.right() - 16, labelRect.top(), 16, 16, QPixmap(":/icons/disconnected.png")); labelRect.adjust(0, 0, -18, 0); } else if (fileStatus == BaseFile::Repairing) { sp.drawPixmap(labelRect.right() - 16, labelRect.top(), 16, 16, QPixmap(":/icons/resync.png")); labelRect.adjust(0, 0, -18, 0); } if (file->getProgress() > -1) { // Show a progress bar while loading the file... QStyleOptionProgressBar so; #ifdef Q_OS_MAC int topOffset = 0; #else int topOffset = 2; #endif so.rect = QRect(labelRect.right() - 32, labelRect.top() + topOffset, 32, labelRect.height() - 4); so.direction = Qt::LeftToRight; so.minimum = 0; so.maximum = 100; so.progress = file->getProgress(); sp.drawControl(QStyle::CE_ProgressBar, so); labelRect.adjust(0, 0, -34, 0); } // Draw the icon location.getIcon().paint(&sp, labelRect.left(), labelRect.top(), 16, 16); labelRect.adjust(16, 0, 0, 0); } // Add some padding around the text... labelRect.adjust(2, 0, -2, 0); // Actually draw the text QFontMetrics fontMetrics = option.fontMetrics; if (level == OpenFileTreeModel::Host) { sp.setPen(location.isSudo() ? QColor(0xCE4848) : QColor(0x6490C1)); QFont f = option.font; f.setPointSize(f.pointSize() - 2); f.setItalic(true); f.setBold(true); sp.setFont(f); labelRect.adjust(0, 0, 0, -3); fontMetrics = QFontMetrics(f); sp.drawLine(option.rect.left(), option.rect.bottom() - 2, option.rect.right(), option.rect.bottom() - 2); } else sp.setFont(option.font); if (level == OpenFileTreeModel::File) label = option.fontMetrics.elidedText(label, Qt::ElideMiddle, labelRect.width()); else label = Tools::squashLabel(label, fontMetrics, labelRect.width()); QTextOption o; o.setAlignment(Qt::AlignBottom | Qt::AlignLeft); sp.drawText(labelRect, label, o); } painter->begin(device); } }
void TimelineBar::paintMarkers(QPainter &p, const QVector<Marker> &markers, const QVector<uint32_t> &draws, QRectF markerRect) { if(markers.isEmpty() && draws.isEmpty()) return; QTextOption to; to.setWrapMode(QTextOption::NoWrap); to.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); QFontMetrics fm(Formatter::PreferredFont()); // store a reference of what a completely elided string looks like QString tooshort = fm.elidedText(lit("asd"), Qt::ElideRight, fm.height()); for(const Marker &m : markers) { QRectF r = markerRect; r.setLeft(qMax(m_dataArea.left() + borderWidth * 3, offsetOf(m.eidStart))); r.setRight(qMin(m_dataArea.right() - borderWidth, offsetOf(m.eidEnd + 1))); r.setHeight(fm.height() + borderWidth * 2); if(r.width() <= borderWidth * 2) continue; QColor backColor = m.color; if(r.contains(m_lastPos)) backColor.setAlpha(150); p.setPen(QPen(palette().brush(QPalette::Text), 1.0)); p.fillRect(r, QBrush(backColor)); p.drawRect(r); p.setPen(QPen(QBrush(contrastingColor(backColor, palette().color(QPalette::Text))), 1.0)); r.setLeft(r.left() + margin); int plusWidth = fm.width(QLatin1Char('+')); if(r.width() > plusWidth) { QRectF plusRect = r; plusRect.setWidth(plusWidth); QTextOption plusOption = to; plusOption.setAlignment(Qt::AlignCenter | Qt::AlignVCenter); p.drawText(plusRect, m.expanded ? lit("-") : lit("+"), plusOption); r.setLeft(r.left() + plusWidth + margin); } QString elided = fm.elidedText(m.name, Qt::ElideRight, r.width()); // if everything was elided, just omit the title entirely if(elided == tooshort) elided = QString(); r.setLeft(qRound(r.left() + margin)); p.drawText(r, elided, to); if(m.expanded) { QRectF childRect = r; childRect.setTop(r.bottom() + borderWidth * 2); childRect.setBottom(markerRect.bottom()); paintMarkers(p, m.children, m.draws, childRect); } } p.setRenderHint(QPainter::Antialiasing); for(uint32_t d : draws) { QRectF r = markerRect; r.setLeft(qMax(m_dataArea.left() + borderWidth * 3, offsetOf(d))); r.setRight(qMin(m_dataArea.right() - borderWidth, offsetOf(d + 1))); r.setHeight(fm.height() + borderWidth * 2); QPainterPath path; path.addRoundedRect(r, 5, 5); p.setPen(QPen(palette().brush(QPalette::Text), 1.0)); p.fillPath(path, d == m_Ctx.CurEvent() ? Qt::green : Qt::blue); p.drawPath(path); } p.setRenderHint(QPainter::Antialiasing, false); }
void TimelineBar::paintEvent(QPaintEvent *e) { QPainter p(viewport()); p.setFont(font()); p.setRenderHint(QPainter::TextAntialiasing); // draw boundaries and background { QRectF r = viewport()->rect(); p.fillRect(r, palette().brush(QPalette::Window)); r = r.marginsRemoved(QMargins(borderWidth + margin, borderWidth + margin, borderWidth + margin, borderWidth + margin)); p.fillRect(r, palette().brush(QPalette::Base)); p.drawRect(r); } QTextOption to; to.setWrapMode(QTextOption::NoWrap); to.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); QFontMetrics fm = p.fontMetrics(); { QRectF titleRect = m_eidAxisRect; titleRect.setLeft(titleRect.left() - m_titleWidth); titleRect.setWidth(m_titleWidth); p.setPen(QPen(palette().brush(QPalette::Text), 1.0)); // add an extra margin for the text p.drawText(titleRect.marginsRemoved(QMarginsF(margin, 0, 0, 0)), eidAxisTitle, to); titleRect.setLeft(titleRect.left() - margin); titleRect.setTop(titleRect.top() - margin); p.drawLine(titleRect.bottomLeft(), titleRect.bottomRight()); p.drawLine(titleRect.topRight(), titleRect.bottomRight()); } QRectF eidAxisRect = m_eidAxisRect; p.drawLine(eidAxisRect.bottomLeft(), eidAxisRect.bottomRight() + QPointF(margin, 0)); p.drawLine(m_highlightingRect.topLeft(), m_highlightingRect.topRight()); if(m_Draws.isEmpty()) return; eidAxisRect.setLeft(m_eidAxisRect.left() + m_pan); uint32_t maxEID = m_Draws.isEmpty() ? 0 : m_Draws.back(); to.setAlignment(Qt::AlignCenter | Qt::AlignVCenter); p.setFont(Formatter::PreferredFont()); QRectF hoverRect = eidAxisRect; // clip labels to the visible section p.setClipRect(m_eidAxisRect.marginsAdded(QMargins(0, margin, margin, 0))); // draw where we're hovering { QPoint pos = viewport()->mapFromGlobal(QCursor::pos()); if(m_dataArea.contains(pos)) { uint32_t hoverEID = eventAt(pos.x()); hoverRect.setLeft(offsetOf(hoverEID)); hoverRect.setWidth(m_eidAxisLabelWidth); // recentre hoverRect.moveLeft(hoverRect.left() - m_eidAxisLabelWidth / 2 + m_eidWidth / 2); QColor backCol = palette().color(QPalette::Base); if(getLuminance(backCol) < 0.2f) backCol = backCol.lighter(120); else backCol = backCol.darker(120); QRectF backRect = hoverRect.marginsAdded(QMargins(0, margin - borderWidth, 0, 0)); backRect.setLeft(qMax(backRect.left(), m_eidAxisRect.left() + 1)); p.fillRect(backRect, backCol); p.drawText(hoverRect, QString::number(hoverEID), to); // re-add the top margin so the lines match up with the border around the EID axis hoverRect = hoverRect.marginsAdded(QMargins(0, margin, 0, 0)); if(hoverRect.left() >= m_eidAxisRect.left()) p.drawLine(hoverRect.topLeft(), hoverRect.bottomLeft()); p.drawLine(hoverRect.topRight(), hoverRect.bottomRight()); // shrink the rect a bit for clipping against labels below hoverRect.setX(qRound(hoverRect.x() + 0.5)); hoverRect.setWidth(int(hoverRect.width())); } else { hoverRect = QRectF(); } } QRectF labelRect = eidAxisRect; labelRect.setWidth(m_eidAxisLabelWidth); // iterate through the EIDs from 0, starting from possible a negative offset if the user has // panned to the right. for(uint32_t i = 0; i <= maxEID; i += m_eidAxisLabelStep) { labelRect.moveLeft(offsetOf(i) - labelRect.width() / 2 + m_eidWidth / 2); // check if this label is visible at all, but don't draw labels that intersect with the hovered // number if(labelRect.right() >= 0 && !labelRect.intersects(hoverRect)) p.drawText(labelRect, QString::number(i), to); // check if labelRect is off the edge of the screen if(labelRect.left() >= m_eidAxisRect.right()) break; } // stop clipping p.setClipRect(viewport()->rect()); // clip the markers p.setClipRect(m_markerRect); { QPen pen = p.pen(); paintMarkers(p, m_RootMarkers, m_RootDraws, m_markerRect); p.setPen(pen); } // stop clipping p.setClipRect(viewport()->rect()); QRectF currentRect = eidAxisRect; // draw the current label and line { uint32_t curEID = m_Ctx.CurEvent(); currentRect.setLeft(offsetOf(curEID)); currentRect.setWidth( qMax(m_eidAxisLabelWidth, m_eidAxisLabelTextWidth + dataBarHeight + margin * 2)); // recentre currentRect.moveLeft(currentRect.left() - currentRect.width() / 2 + m_eidWidth / 2); // remember where the middle would have been, without clamping qreal realMiddle = currentRect.center().x(); // clamp the position from the left or right side if(currentRect.left() < eidAxisRect.left()) currentRect.moveLeft(eidAxisRect.left()); else if(currentRect.right() > eidAxisRect.right()) currentRect.moveRight(eidAxisRect.right()); // re-add the top margin so the lines match up with the border around the EID axis QRectF currentBackRect = currentRect.marginsAdded(QMargins(0, margin, 0, 0)); p.fillRect(currentBackRect, palette().brush(QPalette::Base)); p.drawRect(currentBackRect); // draw the 'current marker' pixmap const QPixmap &px = Pixmaps::flag_green(devicePixelRatio()); p.drawPixmap(currentRect.topLeft() + QPointF(margin, 1), px, px.rect()); // move to where the text should be and draw it currentRect.setLeft(currentRect.left() + margin * 2 + dataBarHeight); p.drawText(currentRect, QString::number(curEID), to); // draw a line from the bottom of the shadow downwards QPointF currentTop = currentRect.center(); currentTop.setX(int(qBound(eidAxisRect.left(), realMiddle, eidAxisRect.right() - 2.0)) + 0.5); currentTop.setY(currentRect.bottom()); QPointF currentBottom = currentTop; currentBottom.setY(m_markerRect.bottom()); p.drawLine(currentTop, currentBottom); } to.setAlignment(Qt::AlignLeft | Qt::AlignTop); if(!m_UsageTarget.isEmpty() || !m_HistoryTarget.isEmpty()) { p.setRenderHint(QPainter::Antialiasing); QRectF highlightLabel = m_highlightingRect.marginsRemoved(uniformMargins(margin)); highlightLabel.setX(highlightLabel.x() + margin); QString text; if(!m_HistoryTarget.isEmpty()) text = tr("Pixel history for %1").arg(m_HistoryTarget); else text = tr("Usage for %1:").arg(m_UsageTarget); p.drawText(highlightLabel, text, to); const int triRadius = fm.averageCharWidth(); const int triHeight = fm.ascent(); QPainterPath triangle; triangle.addPolygon( QPolygonF({QPoint(0, triHeight), QPoint(triRadius * 2, triHeight), QPoint(triRadius, 0)})); triangle.closeSubpath(); enum { ReadUsage, WriteUsage, ReadWriteUsage, ClearUsage, BarrierUsage, HistoryPassed, HistoryFailed, UsageCount, }; const QColor colors[UsageCount] = { // read QColor(Qt::red), // write QColor(Qt::green), // read/write QColor(Qt::yellow), // clear QColor(Qt::blue), // barrier QColor(Qt::magenta), // pass QColor(Qt::green), // fail QColor(Qt::red), }; // draw the key if(m_HistoryTarget.isEmpty()) { // advance past the first text to draw the key highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); text = lit(" Reads ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); QPainterPath path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[ReadUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); text = lit(" ), Writes ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[WriteUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); text = lit(" ), Read/Write ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[ReadWriteUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); if(m_Ctx.CurPipelineState().SupportsBarriers()) { text = lit(" ) Barriers ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[BarrierUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); } text = lit(" ), and Clears ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[ClearUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); text = lit(" )"); p.drawText(highlightLabel, text, to); } PipRanges pipranges[UsageCount]; QRectF pipsRect = m_highlightingRect.marginsRemoved(uniformMargins(margin)); pipsRect.setX(pipsRect.x() + margin + m_titleWidth); pipsRect.setHeight(triHeight + margin); pipsRect.moveBottom(m_highlightingRect.bottom()); p.setClipRect(pipsRect); qreal leftClip = -triRadius * 2.0; qreal rightClip = pipsRect.width() + triRadius * 10.0; if(!m_HistoryEvents.isEmpty()) { for(const PixelModification &mod : m_HistoryEvents) { qreal pos = offsetOf(mod.eventId) + m_eidWidth / 2 - triRadius; if(pos < leftClip || pos > rightClip) continue; if(mod.Passed()) pipranges[HistoryPassed].push(pos, triRadius); else pipranges[HistoryFailed].push(pos, triRadius); } } else { for(const EventUsage &use : m_UsageEvents) { qreal pos = offsetOf(use.eventId) + m_eidWidth / 2 - triRadius; if(pos < leftClip || pos > rightClip) continue; if(((int)use.usage >= (int)ResourceUsage::VS_RWResource && (int)use.usage <= (int)ResourceUsage::All_RWResource) || use.usage == ResourceUsage::GenMips || use.usage == ResourceUsage::Copy || use.usage == ResourceUsage::Resolve) { pipranges[ReadWriteUsage].push(pos, triRadius); } else if(use.usage == ResourceUsage::StreamOut || use.usage == ResourceUsage::ResolveDst || use.usage == ResourceUsage::ColorTarget || use.usage == ResourceUsage::DepthStencilTarget || use.usage == ResourceUsage::CopyDst) { pipranges[WriteUsage].push(pos, triRadius); } else if(use.usage == ResourceUsage::Clear) { pipranges[ClearUsage].push(pos, triRadius); } else if(use.usage == ResourceUsage::Barrier) { pipranges[BarrierUsage].push(pos, triRadius); } else { pipranges[ReadUsage].push(pos, triRadius); } } } for(int i = 0; i < UsageCount; i++) { QPainterPath path = pipranges[i].makePath(triRadius, triHeight, pipsRect.y()); if(!path.isEmpty()) { p.drawPath(path); p.fillPath(path, colors[i]); } } } else { QRectF highlightLabel = m_highlightingRect; highlightLabel = highlightLabel.marginsRemoved(uniformMargins(margin)); highlightLabel.setX(highlightLabel.x() + margin); p.drawText(highlightLabel, tr("No resource selected for highlighting."), to); } }
void FrameView::paintEvent(QPaintEvent *) { const int px_unit = font.pixelSize(); const int px_hspace = px_unit * horizontal_factor; const int px_vspace = px_unit * vertical_factor; const int y_offset = viewport()->height()/2 - px_vspace/2; const DocInfo *dinfo = gui::activeDocInfo(); m_currentFrame = dinfo->currentFrame(); m_currentChannel = dinfo->currentChannel(); int currentFrame = m_currentFrame; int currentChannel = m_currentChannel; const int frame_y_offset = y_offset - currentFrame*px_vspace; const QColor bg = stylecolor(styles::PATTERN_BG); QPainter p; p.begin(viewport()); p.setPen(Qt::NoPen); p.setBrush(bg); p.drawRect(rect()); { QLinearGradient lg(0, 0, 0, 1); lg.setColorAt(0, QColor(96, 96, 96)); lg.setColorAt(1, QColor(64, 64, 64)); lg.setCoordinateMode(QGradient::ObjectBoundingMode); p.setBrush(lg); p.drawRect(0, y_offset, viewport()->width(), px_vspace); } { p.setBrush(QColor(255,255,255,64)); p.drawRect(px_hspace*(currentChannel+1), y_offset, px_hspace, px_vspace); } p.setFont(font); QTextOption opt; opt.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); const QColor framenumcol = stylecolor(styles::PATTERN_HIGHLIGHT2_FG, true); p.setPen(framenumcol); p.setBrush(Qt::NoBrush); FtmDocument *d = activeDocument(); int chans = 0; if (d != NULL) { chans = d->GetAvailableChannels(); } int num_frames = d->GetFrameCount(); int viewport_height = viewport()->height(); for (int i = 0; i < num_frames; i++) { int y = px_vspace*i+frame_y_offset; if (y+px_vspace < 0) continue; if (y > viewport_height) break; char buf[6]; sprintf(buf, "%02X", i); p.drawText(QRect(0,y,px_hspace,px_vspace), buf, opt); } unsigned int active_patterns[MAX_CHANNELS]; for (int i = 0; i < chans; i++) { active_patterns[i] = d->GetPatternAtFrame(currentFrame, i); } const QColor selectedpat = stylecolor(styles::PATTERN_FG, true); const QColor unselectedpat = stylecolor(styles::PATTERN_FG, false); for (int i = 0; i < num_frames; i++) { int y = px_vspace*i+frame_y_offset; if (y+px_vspace < 0) continue; if (y > viewport_height) break; for (int x = 0; x < chans; x++) { char buf[6]; int pattern = d->GetPatternAtFrame(i, x); if (pattern == active_patterns[x]) { p.setPen(selectedpat); } else { p.setPen(unselectedpat); } sprintf(buf, "%02X", pattern); p.drawText(QRect(px_hspace*(x+1),y,px_hspace,px_vspace), buf, opt); } } p.setPen(Qt::gray); p.drawLine(px_hspace,0,px_hspace,viewport()->height()); p.end(); }
void TextDocumentLayout::layoutBlock(const QTextBlock &block) { QTextDocument *doc = document(); qreal margin = doc->documentMargin(); qreal blockMaximumWidth = 0; qreal height = 0; QTextLayout *tl = block.layout(); QTextOption option = doc->defaultTextOption(); tl->setTextOption(option); int extraMargin = 0; if (option.flags() & QTextOption::AddSpaceForLineAndParagraphSeparators) { QFontMetrics fm(block.charFormat().font()); extraMargin += fm.width(QChar(0x21B5)); } tl->beginLayout(); qreal availableWidth = d->width; if (availableWidth <= 0) { availableWidth = qreal(INT_MAX); // similar to text edit with pageSize.width == 0 } availableWidth -= 2*margin + extraMargin; qreal indentMargin = 0; while (1) { QTextLine line = tl->createLine(); if (!line.isValid()) break; line.setLeadingIncluded(true); line.setLineWidth(availableWidth - indentMargin); line.setPosition(QPointF(margin + indentMargin, height)); if(!height) //enter only in the first iteration { indentMargin = indentWidth(block); } height += line.height(); blockMaximumWidth = qMax(blockMaximumWidth, line.naturalTextWidth() + 2*margin); } tl->endLayout(); int previousLineCount = doc->lineCount(); const_cast<QTextBlock&>(block).setLineCount(block.isVisible() ? tl->lineCount() : 0); int lineCount = doc->lineCount(); bool emitDocumentSizeChanged = previousLineCount != lineCount; if (blockMaximumWidth > d->maximumWidth) { // new longest line d->maximumWidth = blockMaximumWidth; d->maximumWidthBlockNumber = block.blockNumber(); emitDocumentSizeChanged = true; } else if (block.blockNumber() == d->maximumWidthBlockNumber && blockMaximumWidth < d->maximumWidth) { // longest line shrinking QTextBlock b = doc->firstBlock(); d->maximumWidth = 0; QTextBlock maximumBlock; while (b.isValid()) { qreal blockMaximumWidth = blockWidth(b); if (blockMaximumWidth > d->maximumWidth) { d->maximumWidth = blockMaximumWidth; maximumBlock = b; } b = b.next(); } if (maximumBlock.isValid()) { d->maximumWidthBlockNumber = maximumBlock.blockNumber(); emitDocumentSizeChanged = true; } } if (emitDocumentSizeChanged)// && !d->blockDocumentSizeChanged) emit documentSizeChanged(documentSize()); emit updateBlock(block); }
static QTextOption makeRubyOption() { QTextOption opt; opt.setAlignment(Qt::AlignBottom | Qt::AlignHCenter); opt.setWrapMode(QTextOption::NoWrap); return opt; }
QRect StyleHelper::drawText(QPainter* p, const QRect& rc, QString& str, int nLines, int nFlags, const QColor& color, const QFont& font, bool bElided) { if (str.isEmpty()) { qDebug() << "[WARNING]: the text should not be empty when drawing!"; return QRect(); } QFontMetrics fm(font); if (rc.height() < (fm.height() + fm.leading()) * nLines) { qDebug() << "[WARNING]: space is not enough for drawing! text: " << str.left(30) << "..."; } //if (rc.width() * nLines < fm.width(str)) { // qDebug() << "[WARNING]: width should bigger than font metrics when drawing! text:" << str.left(30) << "..."; //} p->save(); p->setPen(color); p->setFont(font); int nWidth = 0; int nHeight = 0; int nHeightLine = p->fontMetrics().height() + leading(); QRect rcRet(rc.x(), rc.y(), rc.width(), nHeightLine); rcRet.adjust(margin(), 0, -margin(), 0); QTextLayout textLayout(str, p->font()); QTextOption opt = textLayout.textOption(); opt.setWrapMode(QTextOption::WrapAnywhere); textLayout.setTextOption(opt); textLayout.beginLayout(); while (nLines) { QTextLine line = textLayout.createLine(); if (!line.isValid()) { break; } line.setLineWidth(rcRet.width()); QString lineText; if (nLines == 1 && bElided) { // the last line lineText = p->fontMetrics().elidedText(str, Qt::ElideRight, rcRet.width()); nWidth = qMax<int>(p->fontMetrics().width(lineText), nWidth); } else { lineText = str.left(line.textLength()); nWidth = qMax<int>(line.width(), nWidth); } str.remove(0, line.textLength()); p->drawText(rcRet, nFlags, lineText); nHeight += nHeightLine; rcRet.setRect(rc.x(), rc.y() + nHeight, nWidth, nHeightLine); rcRet.adjust(margin(), 0, -margin(), 0); nLines--; } textLayout.endLayout(); rcRet.setRect(rc.x() + margin(), rc.y(), nWidth + margin(), nHeight); //rcRet.adjust(margin(), 0, -margin(), 0); p->restore(); return rcRet; }
void StickyNoteActor::syncStickyNoteWithFileContents() { reauthorize(false); // clear the old texture #ifdef DXRENDER SAFE_RELEASE(_stickyNoteTextureId); #else if (_stickyNoteTextureId) { glDeleteTextures(1, &_stickyNoteTextureId); _stickyNoteTextureId = 0; } #endif // get the font int fontSize = NxMath::max(20, themeManager->getValueAsInt("ui.stickyNote.font.size",0)); FontDescription desc(themeManager->getValueAsFontFamilyName("ui.stickyNote.font.family",""), fontSize); QFont stickyNoteFont = fontManager->getFont(desc); // get the sticky note text QString stickyNoteStr; getStickyNote(getFullPath(), &stickyNoteStr); // layout the sticky note text QTextOption option; option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); _stickyNoteText.setDefaultTextOption(option); _stickyNoteText.setDefaultFont(stickyNoteFont); _stickyNoteText.setDocumentMargin(12.5f); _stickyNoteText.setTextWidth(256); _stickyNoteText.setPlainText(stickyNoteStr); QSizeF textSize = _stickyNoteText.size(); const int minStickyNoteFontSize = 10; while (textSize.height() > 256 && stickyNoteFont.pointSize() > minStickyNoteFontSize) { stickyNoteFont.setPointSize(stickyNoteFont.pointSize() - 1); _stickyNoteText.setDefaultFont(stickyNoteFont); textSize = _stickyNoteText.size(); } // render the sticky note to a qimage const unsigned int bufferSize = 256; QImage image(bufferSize, bufferSize, QImage::Format_ARGB32); image.fill(Qt::red); QPainter p; p.begin(&image); p.setRenderHint(QPainter::Antialiasing, true); p.setRenderHint(QPainter::TextAntialiasing, true); p.drawImage(0, 0, _stickyNoteBackground); p.setPen(QColor(50, 50, 75)); _stickyNoteText.drawContents(&p, QRect(0, 0, bufferSize, int(bufferSize - _stickyNoteText.documentMargin()))); p.end(); #ifdef DXRENDER _stickyNoteTextureId = dxr->createTextureFromData(image.width(), image.height(), image.bits(), image.bytesPerLine()); #else // load the qimage into open gl glGenTextures(1, &_stickyNoteTextureId); glBindTexture(GL_TEXTURE_2D, _stickyNoteTextureId); float maximumAnisotropy = 0.0f; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnisotropy); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maximumAnisotropy); if (GLEW_ARB_texture_border_clamp) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER_ARB); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER_ARB); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // copy the full image (glTexSubImage2D does not work well with GL_GENERATE_MIPMAP) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); #endif }
QBalloonTip::QBalloonTip(QSystemTrayIcon::MessageIcon icon, const QString& title, const QString& message, QSystemTrayIcon *ti) : QWidget(0, Qt::ToolTip), trayIcon(ti), timerId(-1) { setAttribute(Qt::WA_DeleteOnClose); QObject::connect(ti, SIGNAL(destroyed()), this, SLOT(close())); QLabel *titleLabel = new QLabel; titleLabel->installEventFilter(this); titleLabel->setText(title); QFont f = titleLabel->font(); f.setBold(true); #ifdef Q_WS_WINCE f.setPointSize(f.pointSize() - 2); #endif titleLabel->setFont(f); titleLabel->setTextFormat(Qt::PlainText); // to maintain compat with windows #ifdef Q_WS_WINCE const int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize); const int closeButtonSize = style()->pixelMetric(QStyle::PM_SmallIconSize) - 2; #else const int iconSize = 18; const int closeButtonSize = 15; #endif QPushButton *closeButton = new QPushButton; closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); closeButton->setIconSize(QSize(closeButtonSize, closeButtonSize)); closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); closeButton->setFixedSize(closeButtonSize, closeButtonSize); QObject::connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); QLabel *msgLabel = new QLabel; #ifdef Q_WS_WINCE f.setBold(false); msgLabel->setFont(f); #endif msgLabel->installEventFilter(this); msgLabel->setText(message); msgLabel->setTextFormat(Qt::PlainText); msgLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft); // smart size for the message label #ifdef Q_WS_WINCE int limit = QApplication::desktop()->availableGeometry(msgLabel).size().width() / 2; #else int limit = QApplication::desktop()->availableGeometry(msgLabel).size().width() / 3; #endif if (msgLabel->sizeHint().width() > limit) { msgLabel->setWordWrap(true); if (msgLabel->sizeHint().width() > limit) { msgLabel->d_func()->ensureTextControl(); if (QTextControl *control = msgLabel->d_func()->control) { QTextOption opt = control->document()->defaultTextOption(); opt.setWrapMode(QTextOption::WrapAnywhere); control->document()->setDefaultTextOption(opt); } } #ifdef Q_WS_WINCE // Make sure that the text isn't wrapped "somewhere" in the balloon widget // in the case that we have a long title label. setMaximumWidth(limit); #else // Here we allow the text being much smaller than the balloon widget // to emulate the weird standard windows behavior. msgLabel->setFixedSize(limit, msgLabel->heightForWidth(limit)); #endif } QIcon si; switch (icon) { case QSystemTrayIcon::Warning: si = style()->standardIcon(QStyle::SP_MessageBoxWarning); break; case QSystemTrayIcon::Critical: si = style()->standardIcon(QStyle::SP_MessageBoxCritical); break; case QSystemTrayIcon::Information: si = style()->standardIcon(QStyle::SP_MessageBoxInformation); break; case QSystemTrayIcon::NoIcon: default: break; } QGridLayout *layout = new QGridLayout; if (!si.isNull()) { QLabel *iconLabel = new QLabel; iconLabel->setPixmap(si.pixmap(iconSize, iconSize)); iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); iconLabel->setMargin(2); layout->addWidget(iconLabel, 0, 0); layout->addWidget(titleLabel, 0, 1); } else { layout->addWidget(titleLabel, 0, 0, 1, 2); } layout->addWidget(closeButton, 0, 2); layout->addWidget(msgLabel, 1, 0, 1, 3); layout->setSizeConstraint(QLayout::SetFixedSize); layout->setMargin(3); setLayout(layout); QPalette pal = palette(); pal.setColor(QPalette::Window, QColor(0xff, 0xff, 0xe1)); pal.setColor(QPalette::WindowText, Qt::black); setPalette(pal); }
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(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()*/); QString client_name = dlg->account()->capsManager()->clientName(caps_jid); QString client_version = (client_name.isEmpty() ? QString() : dlg->account()->capsManager()->clientVersion(caps_jid)); UserResource ur; 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); } 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); } 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 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 PlaylistDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); if ( option.state & QStyle::State_Selected && option.state & QStyle::State_Active ) { opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) ); } painter->save(); painter->setRenderHint( QPainter::Antialiasing ); painter->setPen( opt.palette.color( QPalette::Text ) ); QTextOption to; to.setAlignment( Qt::AlignCenter ); QFont font = opt.font; #ifdef Q_WS_MAC font.setPointSize( font.pointSize() - 2 ); #endif QFont boldFont = font; boldFont.setBold( true ); QPixmap icon; RecentlyPlayedPlaylistsModel::PlaylistTypes type = (RecentlyPlayedPlaylistsModel::PlaylistTypes)index.data( RecentlyPlayedPlaylistsModel::PlaylistTypeRole ).toInt(); if( type == RecentlyPlayedPlaylistsModel::StaticPlaylist ) icon = m_playlistIcon; else if( type == RecentlyPlayedPlaylistsModel::AutoPlaylist ) icon = m_autoIcon; else if( type == RecentlyPlayedPlaylistsModel::Station ) icon = m_stationIcon; QRect pixmapRect = option.rect.adjusted( 10, 13, -option.rect.width() + 48, -13 ); icon = icon.scaled( pixmapRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation ); painter->drawPixmap( pixmapRect, icon ); if ( type != RecentlyPlayedPlaylistsModel::Station ) { painter->save(); QString tracks = index.data( RecentlyPlayedPlaylistsModel::TrackCountRole ).toString(); int width = painter->fontMetrics().width( tracks ); // int bottomEdge = pixmapRect // right edge 10px past right edge of pixmapRect // bottom edge flush with bottom of pixmap QRect rect( pixmapRect.right() - width , 0, width - 8, 0 ); rect.adjust( -1, 0, 0, 0 ); rect.setTop( pixmapRect.bottom() - painter->fontMetrics().height() - 1 ); rect.setBottom( pixmapRect.bottom() + 1 ); QColor figColor( 153, 153, 153 ); painter->setPen( figColor ); painter->setBrush( figColor ); painter->setFont( boldFont ); TomahawkUtils::drawBackgroundAndNumbers( painter, tracks, rect ); painter->restore(); } QPixmap avatar = index.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >()->author()->avatar( Source::FancyStyle ); if ( avatar.isNull() ) avatar = m_defaultAvatar; QRect r( option.rect.width() - avatar.width() - 10, option.rect.top() + option.rect.height()/2 - avatar.height()/2, avatar.width(), avatar.height() ); painter->drawPixmap( r, avatar ); QFont font2 = font; font2.setPointSize( font2.pointSize() - 1 ); painter->setFont( font2 ); QString author = index.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >()->author()->friendlyName(); if ( author.contains( "@" ) ) author = author.mid( 0, author.indexOf( '@' ) ); const int w = painter->fontMetrics().width( author ); QRect avatarNameRect( opt.rect.width() - 10 - w, r.bottom(), w, opt.rect.bottom() - r.bottom() ); painter->drawText( avatarNameRect, author, QTextOption( Qt::AlignCenter ) ); const int leftEdge = opt.rect.width() - qMin( avatarNameRect.left(), r.left() ); QString descText; if ( type == RecentlyPlayedPlaylistsModel::Station ) { descText = index.data( RecentlyPlayedPlaylistsModel::DynamicPlaylistRole ).value< Tomahawk::dynplaylist_ptr >()->generator()->sentenceSummary(); } else { descText = index.data( RecentlyPlayedPlaylistsModel::ArtistRole ).toString(); } QColor c = painter->pen().color(); painter->setPen( QColor( Qt::gray ).darker() ); QRect rectText = option.rect.adjusted( 66, 20, -leftEdge - 10, -8 ); #ifdef Q_WS_MAC rectText.adjust( 0, 1, 0, 0 ); #elif defined Q_WS_WIN rectText.adjust( 0, 2, 0, 0 ); #endif painter->drawText( rectText, descText ); painter->setPen( c ); painter->setFont( font ); painter->setFont( boldFont ); painter->drawText( option.rect.adjusted( 56, 6, -100, -option.rect.height() + 20 ), index.data().toString() ); 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(); }
// if painter is nullptr, the method calculate the bounding rectangle of the text and save it to textRect void FolderItemDelegate::drawText(QPainter* painter, QStyleOptionViewItemV4& opt, QRectF& textRect) const { 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()); if(visibleLines == 1) // this is the only visible line width = textRect.width(); break; } height += line.height(); width = qMax(width, line.naturalTextWidth()); ++ visibleLines; } layout.endLayout(); // draw background for selected item QRectF boundRect = layout.boundingRect(); //qDebug() << "bound rect: " << boundRect << "width: " << width; boundRect.setWidth(width); boundRect.moveTo(textRect.x() + (textRect.width() - width)/2, textRect.y()); if(!painter) { // no painter, calculate the bounding rect only textRect = boundRect; return; } QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if(opt.state & QStyle::State_Selected) { painter->fillRect(boundRect, opt.palette.highlight()); painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else painter->setPen(opt.palette.color(cg, QPalette::Text)); // 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) { // draw focus rect QStyleOptionFocusRect o; o.QStyleOption::operator=(opt); o.rect = boundRect.toRect(); // subElementRect(SE_ItemViewItemFocusRect, vopt, 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); if (const QWidget* widget = opt.widget) { QStyle* style = widget->style() ? widget->style() : qApp->style(); style->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, widget); } } }
FaceItem::FaceItem(QGraphicsItem* const parent, QGraphicsScene* const scene, const QRect& rect, double scale, const QString& name, double originalscale) : QGraphicsObject(parent), d(new Private) { setAcceptHoverEvents(true); d->origScale = originalscale; d->scale = scale; d->origRect = rect; d->sceneWidth = scene->width(); d->sceneHeight = scene->height(); // Scale all coordinates to fit the initial size of the scene d->x1 = rect.topLeft().x() * scale; d->y1 = rect.topLeft().y() * scale; d->x2 = rect.bottomRight().x() * scale; d->y2 = rect.bottomRight().y() * scale; // A QRect containing coordinates for the face rectangle QRect scaledRect; scaledRect.setTopLeft(QPoint(d->x1, d->y1)); scaledRect.setBottomRight(QPoint(d->x2, d->y2)); // marquee FancyRect* const fancy = new FancyRect(scaledRect); d->faceMarquee = new Marquee(fancy); scene->addItem(d->faceMarquee); // Make a new QGraphicsTextItem for writing the name text, and a new QGraphicsRectItem to draw a good-looking, semi-transparent bounding box. d->nameRect = new QGraphicsRectItem(0); scene->addItem(d->nameRect); d->faceName = new QGraphicsTextItem(name, 0); scene->addItem(d->faceName); // Make the bounding box for the name update itself to cover all the text whenever contents are changed QTextDocument* const doc = d->faceName->document(); QTextOption o; o.setAlignment(Qt::AlignCenter); doc->setDefaultTextOption(o); // Get coordinates of the name relative the the scene QRectF r = d->faceName->mapRectToScene(d->faceName->boundingRect()); // Draw the bounding name rectangle with the scene coordinates d->nameRect->setRect(r); QPen p(QColor(QString::fromLatin1("white"))); p.setWidth(3); d->nameRect->setPen(p); d->nameRect->setBrush(QBrush(QColor(QString::fromLatin1("black")))); d->nameRect->setOpacity(0.6); d->nameRect->show(); // Draw the name input item d->faceName->setDefaultTextColor(QColor(QString::fromLatin1("white"))); d->faceName->setFont(QFont(QString::fromLatin1("Helvetica"), 9)); d->faceName->setTextInteractionFlags(Qt::TextEditorInteraction); d->faceName->setOpacity(1); //--------------------- QPixmap rejectPix = QIcon::fromTheme(QString::fromLatin1("window-close")).pixmap(16, 16); d->rejectButton = new Button( rejectPix, rejectPix); scene->addItem(d->rejectButton); d->rejectButton->show(); QPixmap acceptPix = QIcon::fromTheme(QString::fromLatin1("dialog-ok-apply")).pixmap(16, 16); d->acceptButton = new Button( acceptPix, acceptPix); scene->addItem(d->acceptButton); //d->acceptButton->show(); d->suggestionRejectButton = new Button(rejectPix, rejectPix); scene->addItem(d->suggestionRejectButton); //d->suggestionAcceptButton->hide(); d->suggestionAcceptButton = new Button(acceptPix, acceptPix); scene->addItem(d->suggestionAcceptButton); //d->suggestionRejectButton->hide(); update(); switchToEditMode(); d->acceptButton->hide(); connect(d->rejectButton, &Button::clicked, this, &FaceItem::reject); connect(d->acceptButton, &Button::clicked, this, &FaceItem::accepted); connect(d->suggestionAcceptButton, &Button::clicked, this, &FaceItem::slotSuggestionAccepted); connect(d->suggestionRejectButton, &Button::clicked, this, &FaceItem::slotSuggestionRejected); connect(doc, SIGNAL(contentsChanged()), this, SLOT(update())); connect(d->faceMarquee, &Marquee::changed, this, &FaceItem::update); }
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 ); // painter->drawPixmap( option.rect.adjusted( 4, 4, -4, -38 ), m_shadowPixmap ); 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; QFont boldFont = opt.font; boldFont.setBold( true ); QRect textRect = option.rect.adjusted( 0, option.rect.height() - 32, 0, -2 ); bool 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( item->album()->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 ); painter->setFont( boldFont ); to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom ); text = painter->fontMetrics().elidedText( item->album()->artist()->name(), Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); } painter->restore(); }
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; 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(); bottom = item->query()->artist(); } else { return; } painter->save(); painter->setRenderHint( QPainter::Antialiasing ); 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.0 ); opacity = 0.35 - pct * 0.35; } else if ( m_hoverIndex == index ) { opacity = 0.35; } if ( opacity > -1.0 ) { painter->save(); painter->setPen( QColor( "dddddd" ) ); painter->setBrush( QColor( "#dddddd" ) ); painter->setOpacity( opacity ); painter->drawRect( r ); painter->restore(); } 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 ); int bottomHeight = QFontMetrics( font ).boundingRect( bottom ).height(); int topHeight = QFontMetrics( boldFont ).boundingRect( top ).height(); int frameHeight = bottomHeight + topHeight + 10; QColor c1; c1.setRgb( 0, 0, 0 ); c1.setAlphaF( 0.00 ); QColor c2; c2.setRgb( 0, 0, 0 ); c2.setAlphaF( 0.88 ); QRect gradientRect = r.adjusted( 0, r.height() - frameHeight * 2, 0, 0 ); QLinearGradient gradient( QPointF( 0, 0 ), QPointF( 0, 1 ) ); gradient.setCoordinateMode( QGradient::ObjectBoundingMode ); gradient.setColorAt( 0.0, c1 ); gradient.setColorAt( 0.6, c2 ); gradient.setColorAt( 1.0, c2 ); painter->save(); painter->setPen( Qt::transparent ); painter->setBrush( gradient ); painter->drawRect( gradientRect ); painter->restore(); painter->setPen( TomahawkUtils::Colors::SELECTION_FOREGROUND ); QRect textRect = option.rect.adjusted( 6, option.rect.height() - frameHeight, -6, -6 ); bool oneLiner = false; if ( bottom.isEmpty() ) oneLiner = true; painter->setFont( boldFont ); 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, r ); painter->setPen( TomahawkUtils::Colors::SELECTION_FOREGROUND ); } 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(); }
bool RunWdgView::event( QEvent *event ) { //> Force event's process switch(event->type()) { case QEvent::Paint: if(permView()) break; //> Paint message about access denied if(dynamic_cast<RunPageView*>(this)) { QPainter pnt(this); //>> Fill page and draw border pnt.fillRect(rect(),QBrush(QColor("black"),Qt::Dense4Pattern)); pnt.setPen(QPen(QBrush(QColor("black")),1)); pnt.drawRect(rect().adjusted(0,0,-1,-1)); //>> Draw message QTextOption to; pnt.setPen(QColor("red")); to.setAlignment(Qt::AlignCenter); to.setWrapMode(QTextOption::WordWrap); if( rect().width() > 500 && rect().height() > 100 ) { QFont cfnt = pnt.font(); cfnt.setPointSize( 16 ); pnt.setFont( cfnt ); } pnt.drawText(rect(),QString(_("Page: '%1'.\nView access is not permitted.")).arg(id().c_str()),to); } return true; case QEvent::MouseButtonRelease: if(((QMouseEvent*)event)->button() == Qt::RightButton && !property("contextMenu").toString().isEmpty() && property("active").toBool() && permCntr() && isVisible(mapFromGlobal(cursor().pos()))) { QAction *actTmp; QMenu popup; string sln; for(int off = 0; (sln=TSYS::strSepParse(property("contextMenu").toString().toAscii().data(),0,'\n',&off)).size(); ) { actTmp = new QAction(TSYS::strSepParse(sln,0,':').c_str(),this); actTmp->setWhatsThis(TSYS::strSepParse(sln,1,':').c_str()); popup.addAction(actTmp); } if(!popup.isEmpty()) { actTmp = popup.exec(QCursor::pos()); if(actTmp && !actTmp->whatsThis().isEmpty()) attrSet("event","usr_"+actTmp->whatsThis().toStdString()); popup.clear(); return true; } } break; default: break; } //> Call to shape for event process if(WdgView::event(event) || (shape&&shape->event(this,event))) return true; //> Key events process for send to model string mod_ev; map<string,string> attrs; if(property("active").toBool() && permCntr()) switch(event->type()) { case QEvent::Paint: return true; case QEvent::KeyPress: mod_ev = "key_pres"; case QEvent::KeyRelease: if(((QKeyEvent*)event)->key() == Qt::Key_Tab) { mod_ev = ""; break; } if(mod_ev.empty()) mod_ev = "key_rels"; if(QApplication::keyboardModifiers()&Qt::ControlModifier) mod_ev += "Ctrl"; if(QApplication::keyboardModifiers()&Qt::AltModifier) mod_ev += "Alt"; if(QApplication::keyboardModifiers()&Qt::ShiftModifier) mod_ev += "Shift"; if(((QKeyEvent*)event)->nativeScanCode()) attrs["event"] = mod_ev+"SC#"+TSYS::int2str(((QKeyEvent*)event)->nativeScanCode(),TSYS::Hex); switch(((QKeyEvent*)event)->key()) { case Qt::Key_Escape: mod_ev+="Esc"; break; case Qt::Key_Backspace: mod_ev+="BackSpace"; break; case Qt::Key_Return: mod_ev+="Return"; break; case Qt::Key_Enter: mod_ev+="Enter"; break; case Qt::Key_Insert: mod_ev+="Insert"; break; case Qt::Key_Delete: mod_ev+="Delete"; break; case Qt::Key_Pause: mod_ev+="Pause"; break; case Qt::Key_Print: mod_ev+="Print"; break; //case Qt::Key_SysReq: mod_ev+="SysReq"; break; //case Qt::Key_Clear: mod_ev+="Clear"; break; case Qt::Key_Home: mod_ev+="Home"; break; case Qt::Key_End: mod_ev+="End"; break; case Qt::Key_Left: mod_ev+="Left"; break; case Qt::Key_Up: mod_ev+="Up"; break; case Qt::Key_Right: mod_ev+="Right"; break; case Qt::Key_Down: mod_ev+="Down"; break; case Qt::Key_PageUp: mod_ev+="PageUp"; break; case Qt::Key_PageDown: mod_ev+="PageDown"; break; case Qt::Key_F1: mod_ev+="F1"; break; case Qt::Key_F2: mod_ev+="F2"; break; case Qt::Key_F3: mod_ev+="F3"; break; case Qt::Key_F4: mod_ev+="F4"; break; case Qt::Key_F5: mod_ev+="F5"; break; case Qt::Key_F6: mod_ev+="F6"; break; case Qt::Key_F7: mod_ev+="F7"; break; case Qt::Key_F8: mod_ev+="F8"; break; case Qt::Key_F9: mod_ev+="F9"; break; case Qt::Key_F10: mod_ev+="F10"; break; case Qt::Key_F11: mod_ev+="F11"; break; case Qt::Key_F12: mod_ev+="F12"; break; case Qt::Key_F13: mod_ev+="F13"; break; case Qt::Key_F14: mod_ev+="F14"; break; case Qt::Key_F15: mod_ev+="F15"; break; case Qt::Key_F16: mod_ev+="F16"; break; case Qt::Key_F17: mod_ev+="F17"; break; case Qt::Key_F18: mod_ev+="F18"; break; case Qt::Key_F19: mod_ev+="F19"; break; case Qt::Key_F20: mod_ev+="F20"; break; case Qt::Key_F21: mod_ev+="F21"; break; case Qt::Key_F22: mod_ev+="F22"; break; case Qt::Key_F23: mod_ev+="F23"; break; case Qt::Key_F24: mod_ev+="F24"; break; case Qt::Key_F25: mod_ev+="F25"; break; case Qt::Key_F26: mod_ev+="F26"; break; case Qt::Key_F27: mod_ev+="F27"; break; case Qt::Key_F28: mod_ev+="F28"; break; case Qt::Key_F29: mod_ev+="F29"; break; case Qt::Key_F30: mod_ev+="F30"; break; case Qt::Key_F31: mod_ev+="F31"; break; case Qt::Key_F32: mod_ev+="F32"; break; case Qt::Key_F33: mod_ev+="F33"; break; case Qt::Key_F34: mod_ev+="F34"; break; case Qt::Key_F35: mod_ev+="F35"; break; case Qt::Key_Space: mod_ev+="Space"; break; case Qt::Key_Apostrophe:mod_ev+="Apostrophe"; break; case Qt::Key_Asterisk: mod_ev+="Asterisk"; break; case Qt::Key_Plus: mod_ev+="Plus"; break; case Qt::Key_Comma: mod_ev+="Comma"; break; case Qt::Key_Minus: mod_ev+="Minus"; break; case Qt::Key_Period: mod_ev+="Period"; break; case Qt::Key_Slash: mod_ev+="Slash"; break; case Qt::Key_0: mod_ev+="0"; break; case Qt::Key_1: mod_ev+="1"; break; case Qt::Key_2: mod_ev+="2"; break; case Qt::Key_3: mod_ev+="3"; break; case Qt::Key_4: mod_ev+="4"; break; case Qt::Key_5: mod_ev+="5"; break; case Qt::Key_6: mod_ev+="6"; break; case Qt::Key_7: mod_ev+="7"; break; case Qt::Key_8: mod_ev+="8"; break; case Qt::Key_9: mod_ev+="9"; break; case Qt::Key_Semicolon: mod_ev+="Semicolon"; break; case Qt::Key_Equal: mod_ev+="Equal"; break; case Qt::Key_A: mod_ev+="A"; break; case Qt::Key_B: mod_ev+="B"; break; case Qt::Key_C: mod_ev+="C"; break; case Qt::Key_D: mod_ev+="D"; break; case Qt::Key_E: mod_ev+="E"; break; case Qt::Key_F: mod_ev+="F"; break; case Qt::Key_G: mod_ev+="G"; break; case Qt::Key_H: mod_ev+="H"; break; case Qt::Key_I: mod_ev+="I"; break; case Qt::Key_J: mod_ev+="J"; break; case Qt::Key_K: mod_ev+="K"; break; case Qt::Key_L: mod_ev+="L"; break; case Qt::Key_M: mod_ev+="M"; break; case Qt::Key_N: mod_ev+="N"; break; case Qt::Key_O: mod_ev+="O"; break; case Qt::Key_P: mod_ev+="P"; break; case Qt::Key_Q: mod_ev+="Q"; break; case Qt::Key_R: mod_ev+="R"; break; case Qt::Key_S: mod_ev+="S"; break; case Qt::Key_T: mod_ev+="T"; break; case Qt::Key_U: mod_ev+="U"; break; case Qt::Key_V: mod_ev+="V"; break; case Qt::Key_W: mod_ev+="W"; break; case Qt::Key_X: mod_ev+="X"; break; case Qt::Key_Y: mod_ev+="Y"; break; case Qt::Key_Z: mod_ev+="Z"; break; case Qt::Key_BracketLeft: mod_ev+="BracketLeft"; break; case Qt::Key_Backslash: mod_ev+="BackSlash"; break; case Qt::Key_BracketRight: mod_ev+="BracketRight"; break; case Qt::Key_QuoteLeft: mod_ev+="QuoteLeft"; break; default: mod_ev += "#"+TSYS::int2str(((QKeyEvent*)event)->key(),TSYS::Hex); break; } attrs["event"] += (attrs["event"].size()?"\n":"")+mod_ev; attrsSet(attrs); return true; case QEvent::MouseButtonPress: mod_ev = "key_mousePres"; case QEvent::MouseButtonRelease: if(mod_ev.empty()) mod_ev = "key_mouseRels"; switch(((QMouseEvent*)event)->button()) { case Qt::LeftButton: mod_ev += "Left"; break; case Qt::RightButton: mod_ev += "Right"; break; case Qt::MidButton: mod_ev += "Midle"; break; default: break; } if(isVisible(mapFromGlobal(cursor().pos()))) { if(event->type() == QEvent::MouseButtonPress && !hasFocus()) setFocus(Qt::MouseFocusReason); attrSet("event", mod_ev); return true; } break; case QEvent::MouseButtonDblClick: if(!isVisible(mapFromGlobal(cursor().pos()))) break; attrSet("event", "key_mouseDblClick"); return true; case QEvent::FocusIn: attrs["focus"] = "1"; attrs["event"] = "ws_FocusIn"; attrsSet(attrs); return true; case QEvent::FocusOut: attrs["focus"] = "0"; attrs["event"] = "ws_FocusOut"; attrsSet(attrs); return true; default: break; } //> Try put mouse event to next level widget into same container if(!qobject_cast<RunPageView*>(this) && (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease || event->type() == QEvent::MouseButtonDblClick)) { bool isOk = false; QPoint curp = parentWidget()->mapFromGlobal(cursor().pos()); for(int i_c = parentWidget()->children().size()-1; i_c >= 0; i_c--) { RunWdgView *curwdg = qobject_cast<RunWdgView*>(parentWidget()->children().at(i_c)); if(!curwdg) continue; if(curwdg == this) isOk = true; else if(isOk && curwdg->geometry().contains(curp)) { RunWdgView *wdg = curwdg; curp = wdg->mapFromGlobal(cursor().pos()); for(int i_cr = wdg->children().size()-1; i_cr >= 0; i_cr--) { curwdg = qobject_cast<RunWdgView*>(wdg->children().at(i_cr)); if(curwdg && curwdg->geometry().contains(curp)) { wdg = curwdg; i_cr = wdg->children().size(); curp = wdg->mapFromGlobal(cursor().pos()); } } return QApplication::sendEvent(wdg, event); } } } return QWidget::event(event); }
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); bbox().setRect(0.0, 0.0, size.width(), size.height()); _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 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(); }