本文整理汇总了C++中QTextOption类的典型用法代码示例。如果您正苦于以下问题:C++ QTextOption类的具体用法?C++ QTextOption怎么用?C++ QTextOption使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QTextOption类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: doc
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
}
示例2: Q_ASSERT
// 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());
//.........这里部分代码省略.........
示例3: KTextEdit
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"));
//.........这里部分代码省略.........
示例4: applyStyle
//.........这里部分代码省略.........
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);
}
示例5: initStyleOption
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
//.........这里部分代码省略.........
示例6: data
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);
//.........这里部分代码省略.........
示例7: initStyleOption
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;
//.........这里部分代码省略.........
示例8: paintContact
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);
//.........这里部分代码省略.........
示例9: document
/**
* 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);
}
示例10: QPixmap
//.........这里部分代码省略.........
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);
}
}
示例11: fm
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);
}
示例12: p
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());
//.........这里部分代码省略.........
示例13: viewport
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])
{
//.........这里部分代码省略.........
示例14: document
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);
}
示例15: makeRubyOption
static QTextOption makeRubyOption() {
QTextOption opt;
opt.setAlignment(Qt::AlignBottom | Qt::AlignHCenter);
opt.setWrapMode(QTextOption::NoWrap);
return opt;
}