void XYZTextEditor::textDirection() {
    QTextCursor cursor = m_ui->textEdit->textCursor();
    QTextBlockFormat blockFmt = cursor.blockFormat();

    QTextOption topt = m_ui->textEdit->document()->defaultTextOption();
    if (m_ui->btnTextDirection->isChecked()) {
        topt.setTextDirection(Qt::RightToLeft);
        blockFmt.setLayoutDirection(Qt::RightToLeft);
    } else {
        topt.setTextDirection(Qt::LeftToRight);
        blockFmt.setLayoutDirection(Qt::LeftToRight);
    }
    m_ui->textEdit->document()->setDefaultTextOption(topt);
    cursor.setBlockFormat(blockFmt);
}
예제 #2
0
void QLabelPrivate::ensureTextLayouted() const
{
    if (!textLayoutDirty)
        return;
    ensureTextPopulated();
    Q_Q(const QLabel);
    if (control) {
        QTextDocument *doc = control->document();
        QTextOption opt = doc->defaultTextOption();

        Qt::Alignment align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align));
        opt.setAlignment(align);

        if (this->align & Qt::TextWordWrap)
            opt.setWrapMode(QTextOption::WordWrap);
        else
            opt.setWrapMode(QTextOption::ManualWrap);

        opt.setTextDirection(q->layoutDirection());

        doc->setDefaultTextOption(opt);

        QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
        fmt.setMargin(0);
        doc->rootFrame()->setFrameFormat(fmt);
        doc->setTextWidth(documentRect().width());
    }
    textLayoutDirty = false;
}
예제 #3
0
TextDocument::TextDocument(Id id)
    : d(new TextDocumentPrivate)
{
    QObject::connect(&d->m_document, &QTextDocument::modificationChanged, [this](bool modified) {
        // we only want to update the block revisions when going back to the saved version,
        // e.g. with undo
        if (!modified)
            d->updateRevisions();
        emit changed();
    });

    connect(&d->m_document, &QTextDocument::contentsChanged,
            this, &Core::IDocument::contentsChanged);
    connect(&d->m_document, &QTextDocument::contentsChange,
            this, &TextDocument::contentsChangedWithPosition);

    // set new document layout
    QTextOption opt = d->m_document.defaultTextOption();
    opt.setTextDirection(Qt::LeftToRight);
    opt.setFlags(opt.flags() | QTextOption::IncludeTrailingSpaces
                 | QTextOption::AddSpaceForLineAndParagraphSeparators
                );
    d->m_document.setDefaultTextOption(opt);
    d->m_document.setDocumentLayout(new TextDocumentLayout(&d->m_document));

    if (id.isValid())
        setId(id);

    setSuspendAllowed(true);
}
예제 #4
0
void tst_QComplexText::bidiCursorLogicalMovement()
{
    QFETCH(QString, logical);
    QFETCH(int,  basicDir);

    QTextLayout layout(logical);

    QTextOption option = layout.textOption();
    option.setTextDirection(basicDir == QChar::DirL ? Qt::LeftToRight : Qt::RightToLeft);
    layout.setTextOption(option);
    bool moved;
    int oldPos, newPos = 0;

    do {
        oldPos = newPos;
        newPos = layout.nextCursorPosition(oldPos);
        QVERIFY(newPos >= oldPos);
        moved = (oldPos != newPos);
    } while (moved);

    do {
        oldPos = newPos;
        newPos = layout.previousCursorPosition(oldPos);
        QVERIFY(newPos <= oldPos);
        moved = (oldPos != newPos);
    } while (moved);
}
예제 #5
0
void tst_QComplexText::bidiInvalidCursorNoMovement()
{
    QFETCH(QString, logical);
    QFETCH(int,  basicDir);

    QTextLayout layout(logical);

    QTextOption option = layout.textOption();
    option.setTextDirection(basicDir == QChar::DirL ? Qt::LeftToRight : Qt::RightToLeft);
    layout.setTextOption(option);

    // visual
    QCOMPARE(layout.rightCursorPosition(-1000), -1000);
    QCOMPARE(layout.rightCursorPosition(1000), 1000);

    QCOMPARE(layout.leftCursorPosition(-1000), -1000);
    QCOMPARE(layout.leftCursorPosition(1000), 1000);

    // logical
    QCOMPARE(layout.nextCursorPosition(-1000), -1000);
    QCOMPARE(layout.nextCursorPosition(1000), 1000);

    QCOMPARE(layout.previousCursorPosition(-1000), -1000);
    QCOMPARE(layout.previousCursorPosition(1000), 1000);
}
예제 #6
0
QGraphicsTextItem * GraphicsButton::decorateKey(const QRectF & cell,int group,int level) {
  QString text = m_keydef->getDecoration(group,level);
  QGraphicsTextItem * item = new QGraphicsTextItem(this);

  int scriptCount = 0;
  /// Get the script for the text and use it as CSS selector
  /// selectors are case insensitive
  ///
  QString script;
  if (text.size() == 1) {
    script = UcdScripts::getScript(text.at(0).unicode());
    if ( ! script.isEmpty()) {
      scriptCount = 1;
    }
  }
  else {
    script = UcdScripts::getScript(text,&scriptCount);
    if (scriptCount != 1) {
      script = "default";
    }
  }
  script = script.toCaseFolded();
  if (! m_css.isEmpty())
    item->document()->setDefaultStyleSheet(m_css);
  /// this stops Arabic being moved to the right
  QTextOption topt;
  topt.setTextDirection(Qt::LeftToRight);
  item->document()->setDefaultTextOption(topt);
  QString sep("<br/>");
  QString html;
  QStringList w = text.toHtmlEscaped().split(QChar(' '),QString::SkipEmptyParts);
  //  QFont f("Amiri",30);
  //  item->setFont(f);
  //  html = QString("<html><body><span class=\"%1\">%2</span></body></html>").arg(script).arg(text);
  html = QString("<span class=\"%1\">%2</span>").arg(script).arg(w.join("<br/>"));

  item->setHtml(html);//Html(html);

  QRectF wr = item->boundingRect();

  /// align the text centrally in its bounding rect
  qreal dx = cell.width() - wr.width();
  qreal dy = cell.height() - wr.height();


  if (m_keydef->centerText(group,level)) {
    dy = dy/2;
  }
  else {
    int vpos = m_keydef->getVerticalAdjust(group,level);
    dy += vpos;
  }

  item->setPos(cell.topLeft() + QPointF(dx/2,dy));//dy/2));
  item->setDefaultTextColor(m_textColor);
  this->setBrush(QBrush(m_backgroundUpColor));
  this->setPen(QPen(m_textColor));
  return item;
}
예제 #7
0
int TextOption::setTextDirection ( lua_State * L ) // ( Qt::LayoutDirection direction ) void
{
//Qt::LayoutDirection
	QTextOption* lhs = ValueInstaller2<QTextOption>::check( L, 1 );
	Enums enums(L);
	Qt::LayoutDirection direction =(Qt::LayoutDirection)enums.LayoutDirection( 2 );
	lhs->setTextDirection( direction );
	return 0;
}
예제 #8
0
QTextOption TextLabel::textOption() const
{
    Qt::LayoutDirection direction = QApplication::layoutDirection();
    Qt::Alignment alignment = QStyle::visualAlignment(direction, Qt::AlignLeft | Qt::AlignVCenter);

    QTextOption option;
    option.setTextDirection(direction);
    option.setAlignment(alignment);

    return option;
}
예제 #9
0
static PyObject *meth_QTextOption_setTextDirection(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        Qt::LayoutDirection a0;
        QTextOption *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BE", &sipSelf, sipType_QTextOption, &sipCpp, sipType_Qt_LayoutDirection, &a0))
        {
            sipCpp->setTextDirection(a0);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QTextOption, sipName_setTextDirection, doc_QTextOption_setTextDirection);

    return NULL;
}
예제 #10
0
void tst_QComplexText::bidiCursorMovement()
{
    QFETCH(QString, logical);
    QFETCH(int,  basicDir);

    QTextLayout layout(logical);
    layout.setCacheEnabled(true);

    QTextOption option = layout.textOption();
    option.setTextDirection(basicDir == QChar::DirL ? Qt::LeftToRight : Qt::RightToLeft);
    layout.setTextOption(option);
    layout.setCursorMoveStyle(Qt::VisualMoveStyle);
    bool moved;
    int oldPos, newPos = 0;
    qreal x, newX;

    layout.beginLayout();
    QTextLine line = layout.createLine();
    layout.endLayout();

    newX = line.cursorToX(0);
    do {
        oldPos = newPos;
        x = newX;
        newX = line.cursorToX(oldPos);
        if (basicDir == QChar::DirL) {
            QVERIFY(newX >= x);
            newPos = layout.rightCursorPosition(oldPos);
        } else
        {
            QVERIFY(newX <= x);
            newPos = layout.leftCursorPosition(oldPos);
        }
        moved = (oldPos != newPos);
    } while (moved);
}
예제 #11
0
void messages_widget::startChat(const QString& user_name, const libed2k::net_identifier& np)
{
    QTextEdit* edit = new QTextEdit(this);
    edit->setReadOnly(true);
    QTextOption to;
    to.setTextDirection(Qt::LeftToRight);
    edit->document()->setDefaultTextOption(to);
    int new_tab = tabWidget->addTab(edit, QIcon(":/emule/users/Chat.ico"), user_name);    
    tabWidget->setCurrentIndex(new_tab);

    USER user;
    user.strName = user_name;
    user.netPoint = np;
    user.edit = edit;
    user.nTabNum = new_tab;
    if (connectedPeers.contains(np))
        user.connected = true;
    users.push_back(user);

    addSystemMessage(edit, tr("*** Begin chat: ") + user_name);

    enableButtons();
    textMsg->setFocus();
}
예제 #12
0
TextDocument::TextDocument(Id id)
    : d(new TextDocumentPrivate)
{
    connect(&d->m_document, &QTextDocument::modificationChanged,
            this, &TextDocument::modificationChanged);
    connect(&d->m_document, &QTextDocument::contentsChanged,
            this, &Core::IDocument::contentsChanged);
    connect(&d->m_document, &QTextDocument::contentsChange,
            this, &TextDocument::contentsChangedWithPosition);

    // set new document layout
    QTextOption opt = d->m_document.defaultTextOption();
    opt.setTextDirection(Qt::LeftToRight);
    opt.setFlags(opt.flags() | QTextOption::IncludeTrailingSpaces
            | QTextOption::AddSpaceForLineAndParagraphSeparators
            );
    d->m_document.setDefaultTextOption(opt);
    d->m_document.setDocumentLayout(new TextDocumentLayout(&d->m_document));

    if (id.isValid())
        setId(id);

    setSuspendAllowed(true);
}
예제 #13
0
// 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);
    }
  }
}
예제 #14
0
// 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();
}
예제 #15
0
void RichTextDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);

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

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

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

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

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

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

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

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

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

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

        QPixmapCache::insert(key, pm);
    }

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

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

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

    painter->drawPixmap(x, y, pm);
}
// copied from QItemDelegate to be able to add the 'format' parameter
void HighlightingItemDelegate::drawDisplay(QPainter *painter,
                                           const QStyleOptionViewItem &option,
                                           const QRect &rect, const QString &text,
                                           const QVector<QTextLayout::FormatRange> &format) const
{
    QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
                              ? QPalette::Normal : QPalette::Disabled;
    if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
        cg = QPalette::Inactive;
    if (option.state & QStyle::State_Selected) {
        painter->fillRect(rect, option.palette.brush(cg, QPalette::Highlight));
        painter->setPen(option.palette.color(cg, QPalette::HighlightedText));
    } else {
        painter->setPen(option.palette.color(cg, QPalette::Text));
    }

    if (text.isEmpty())
        return;

    if (option.state & QStyle::State_Editing) {
        painter->save();
        painter->setPen(option.palette.color(cg, QPalette::Text));
        painter->drawRect(rect.adjusted(0, 0, -1, -1));
        painter->restore();
    }

    const QStyleOptionViewItem opt = option;

    const QWidget *widget = option.widget;
    QStyle *style = widget ? widget->style() : QApplication::style();
    const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, nullptr, widget) + 1;
    QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding
    const bool wrapText = opt.features & QStyleOptionViewItem::WrapText;
    QTextOption textOption;
    textOption.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap);
    textOption.setTextDirection(option.direction);
    textOption.setAlignment(QStyle::visualAlignment(option.direction, option.displayAlignment));
    QTextLayout textLayout;
    textLayout.setTextOption(textOption);
    textLayout.setFont(option.font);
    textLayout.setText(replaceNewLine(text));

    QSizeF textLayoutSize = doTextLayout(&textLayout, textRect.width());

    if (textRect.width() < textLayoutSize.width()
        || textRect.height() < textLayoutSize.height()) {
        QString elided;
        int start = 0;
        int end = text.indexOf(QChar::LineSeparator, start);
        if (end == -1) {
            elided += option.fontMetrics.elidedText(text, option.textElideMode, textRect.width());
        } else {
            while (end != -1) {
                elided += option.fontMetrics.elidedText(text.mid(start, end - start),
                                                        option.textElideMode, textRect.width());
                elided += QChar::LineSeparator;
                start = end + 1;
                end = text.indexOf(QChar::LineSeparator, start);
            }
            // let's add the last line (after the last QChar::LineSeparator)
            elided += option.fontMetrics.elidedText(text.mid(start),
                                                    option.textElideMode, textRect.width());
        }
        textLayout.setText(elided);
        textLayoutSize = doTextLayout(&textLayout, textRect.width());
    }

    const QSize layoutSize(textRect.width(), int(textLayoutSize.height()));
    const QRect layoutRect = QStyle::alignedRect(option.direction, option.displayAlignment,
                                                  layoutSize, textRect);
    // if we still overflow even after eliding the text, enable clipping
    if (!hasClipping() && (textRect.width() < textLayoutSize.width()
                           || textRect.height() < textLayoutSize.height())) {
        painter->save();
        painter->setClipRect(layoutRect);
        textLayout.draw(painter, layoutRect.topLeft(), format, layoutRect);
        painter->restore();
    } else {
        textLayout.draw(painter, layoutRect.topLeft(), format, layoutRect);
    }
}
예제 #17
0
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();
}