Example #1
0
void CWizNoteStyle::drawMultiLineListWidgetItem(const QStyleOptionViewItemV4 *vopt, QPainter *p, const CWizMultiLineListWidget *view) const
{
    bool imageAlignLeft = view->imageAlignLeft();
    int imageWidth = view->imageWidth();
    int lineCount = view->lineCount();
    int wrapTextLineText = view->wrapTextLineIndex();
    const QPixmap img = view->itemImage(vopt->index);

    p->save();
    p->setClipRect(vopt->rect);

    QRect textLine = vopt->rect;
    textLine.adjust(4, 0, -4, 0);
    p->setPen(m_colorDocumentsLine);
    p->drawLine(textLine.bottomLeft(), textLine.bottomRight());

    QRect textRect = vopt->rect;
    //QRect textRect = subElementRect(SE_ItemViewItemText, vopt, view);

    // draw the background
    if (vopt->state.testFlag(State_Selected))
    {
        m_multiLineListSelectedItemBackground.Draw(p, vopt->rect, 0);
    }

    if (!img.isNull() && img.width() > 0 && img.height() > 0)
    {
        QRect imageRect = textRect;
        if (imageAlignLeft)
        {
            imageRect.setRight(imageRect.left() + imageWidth + 16);
            imageRect.adjust(4, 4, -4, -4);
            textRect.setLeft(imageRect.right());
        }
        else
        {
            imageRect.setLeft(imageRect.right() - imageWidth + 16);
            imageRect.adjust(4, 4, -4, -4);
            textRect.setRight(imageRect.left());
        }

        if (img.width() > imageRect.width() || img.height() > imageRect.height())
        {
            double fRate = std::min<double>(double(imageRect.width()) / img.width(), double(imageRect.height()) / img.height());
            int newWidth = int(img.width() * fRate);
            int newHeight = int(img.height() * fRate);
            //
            int adjustX = (imageRect.width() - newWidth) / 2;
            int adjustY = (imageRect.height() - newHeight) / 2;
            imageRect.adjust(adjustX, adjustY, -adjustX, -adjustY);
        }
        else
        {
            int adjustX = (imageRect.width() - img.width()) / 2;
            int adjustY = (imageRect.height() - img.height()) / 2;
            imageRect.adjust(adjustX, adjustY, -adjustX, -adjustY);
        }
        p->drawPixmap(imageRect, img);
    }

    // draw the text
    QPalette::ColorGroup cg = vopt->state & QStyle::State_Enabled
                              ? QPalette::Normal : QPalette::Disabled;
    if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
        cg = QPalette::Inactive;

    if (vopt->state & QStyle::State_Selected) {
        p->setPen(vopt->palette.color(cg, QPalette::HighlightedText));
    } else {
        p->setPen(vopt->palette.color(cg, QPalette::Text));
    }
    if (vopt->state & QStyle::State_Editing) {
        p->setPen(vopt->palette.color(cg, QPalette::Text));
        p->drawRect(textRect.adjusted(0, 0, -1, -1));
    }

    textRect.adjust(8, 8, -8, -8);
    bool selected = vopt->state.testFlag(State_Selected);
    int lineHeight = vopt->fontMetrics.height() + 2;

    for (int line = 0; line < wrapTextLineText && line < lineCount; line++)
    {
        QColor color = (0 == line) ? (selected ? m_colorMultiLineListFirstLineSelected : m_colorMultiLineListFirstLine)
            : (selected ? m_colorMultiLineListOtherLineSelected : m_colorMultiLineListOtherLine);
        //
        CString strText = view->itemText(vopt->index, line);
        color = view->itemTextColor(vopt->index, line, selected, color);
        QRect rc = textRect;
        rc.setTop(rc.top() + line * lineHeight);
        rc.setHeight(lineHeight);
        ::WizDrawTextSingleLine(p, rc, strText,  Qt::TextSingleLine | Qt::AlignVCenter, color, true);
    }

    int line = wrapTextLineText;
    if (line < lineCount)
    {
        CString strText = view->itemText(vopt->index, line);
        for (; line < lineCount; line++)
        {
            QColor color = selected ? m_colorMultiLineListOtherLineSelected : m_colorMultiLineListOtherLine;
            //
            color = view->itemTextColor(vopt->index, line, selected, color);
            QRect rc = textRect;
            rc.setTop(rc.top() + line * lineHeight);
            rc.setHeight(lineHeight);
            bool elidedText = (line == lineCount - 1);
            ::WizDrawTextSingleLine(p, rc, strText,  Qt::TextSingleLine | Qt::AlignVCenter, color, elidedText);
        }
    }

    // draw the focus rect
    if (vopt->state & QStyle::State_HasFocus) {
        QStyleOptionFocusRect o;
        o.QStyleOption::operator=(*vopt);
        o.rect = subElementRect(SE_ItemViewItemFocusRect, vopt, view);
        o.state |= QStyle::State_KeyboardFocusChange;
        o.state |= QStyle::State_Item;
        QPalette::ColorGroup cg = (vopt->state & QStyle::State_Enabled)
                                  ? QPalette::Normal : QPalette::Disabled;
        o.backgroundColor = vopt->palette.color(cg, (vopt->state & QStyle::State_Selected)
                                                ? QPalette::Highlight : QPalette::Window);
        proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, p, view);
    }

    //draw extra image
    QRect rcExtra;
    QPixmap pixExtra;
    if (view->itemExtraImage(vopt->index, vopt->rect, rcExtra, pixExtra))
    {
        p->drawPixmap(rcExtra, pixExtra);
    }

    p->restore();
}
Example #2
0
    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);
        }

    }
Example #3
0
void TwoLevelDelegate::paint(QPainter *painter, const QStyleOptionViewItem & option,
        const QModelIndex & index ) const
{
    QString text = index.model()->data(index, Qt::DisplayRole).toString();
    QList< StringPair > subTexts = index.model()->data(index, SubLabelsRole).value<QList<StringPair> >();

    QIcon decoration = qvariant_cast<QIcon>(index.model()->data(index, Qt::DecorationRole));
    QIcon secondaryDecoration = qvariant_cast<QIcon>(index.model()->data(index, SubIconRole));

    bool rtl = QtopiaApplication::layoutDirection() == Qt::RightToLeft ;

    painter->save();

    // fill rect based on row background
    // or assume can be left to list class
    bool selected = (option.state & (QStyle::State_Active | QStyle::State_Selected)) == (QStyle::State_Active | QStyle::State_Selected);
    QBrush baseBrush = selected ? option.palette.highlight() : option.palette.base();
    QBrush textBrush = selected ? option.palette.highlightedText() : option.palette.text();
    QPalette modpalette(option.palette);
    modpalette.setBrush(QPalette::Text, textBrush);
    // To avoid messing with the alternating row color, don't set this...
//    modpalette.setBrush(QPalette::Base, baseBrush);
//    painter->setBrush(baseBrush);

    painter->setPen(textBrush.color());

    if (selected)
        painter->fillRect(option.rect, baseBrush);
    QFont fbold = option.font;
    QFont fsmall = differentFont(option.font, -2);
    QFont fsmallbold = fsmall;
    fbold.setWeight(QFont::Bold);
    fsmallbold.setWeight(QFont::Bold);

    QFontMetrics fboldM(fbold);
    QFontMetrics fsmallM(fsmall);
    QFontMetrics fsmallboldM(fsmallbold);

    int decorationSize = qApp->style()->pixelMetric(QStyle::PM_ListViewIconSize);

    int x = option.rect.x();
    int y = option.rect.y();
    int width = option.rect.width();
    int height = option.rect.height()-1;

    if ( rtl )
        painter->drawPixmap(width-decorationSize, y, decoration.pixmap(decorationSize) );
    else
        painter->drawPixmap(x, y, decoration.pixmap(decorationSize));

    x += decorationSize + 2;
    width -= decorationSize + 2;

    int bcardwidth = 0;
    int bcardbase = y;
    if (!secondaryDecoration.isNull()) {
        bcardwidth = decorationSize;
        bcardbase = y+decorationSize;
        if ( rtl )
            painter->drawPixmap( option.rect.x(), y, secondaryDecoration.pixmap(decorationSize));
        else
            painter->drawPixmap(x+width-bcardwidth, y,secondaryDecoration.pixmap(decorationSize));
    }

    // draw label bold
    painter->setFont(fbold);

    // fit inside available width;
    QRect space;
    if ( rtl )
        space = QRect(option.rect.x() + bcardwidth, y, width-bcardwidth, height);
    else
        space = QRect(x, y, width - bcardwidth, height);

    painter->drawText(space, Qt::AlignLeading, fboldM.elidedText(text, Qt::ElideRight, space.width()));

    y+=fboldM.height();


    QString secText;
    StringPair subLine;

    int headerWidth = 0;
    /* First, calculate the width of all the header sections */
    foreach(subLine, subTexts) {
        if (!subLine.first.isEmpty()) {
            int w = fsmallboldM.boundingRect(subLine.first).width();
            if (w > headerWidth)
                headerWidth = w;
        }
    }
    headerWidth += 4; // a little padding

    int sublineheight = qMax(fsmallM.ascent(), fsmallboldM.ascent()) + qMax(fsmallM.descent(), fsmallboldM.descent()) + 1;
    // per font baseline adjustments, durnit.
    int headbase = 0;
    int valbase = 0;

    if (fsmallM.ascent() > fsmallboldM.ascent())
        headbase = fsmallM.ascent() - fsmallboldM.ascent();
    else
        valbase = fsmallboldM.ascent() - fsmallM.ascent();

    /* Now draw! */
    while (y + sublineheight <= option.rect.bottom() && !subTexts.isEmpty()) {
        if (y > bcardbase) {
            bcardwidth = 0;
            if ( rtl )
                space = QRect(option.rect.x(), y, width, option.rect.bottom() - y + 1);
            else
                space = QRect(x, y, width, option.rect.bottom() - y + 1);
        } else
            space.setTop(y);

        subLine = subTexts.takeFirst();
        if (!subLine.first.isNull()) {
            if (!subLine.second.isEmpty()) {
                QRect headerRect = space.adjusted(0,headbase,0,0);
                QRect valueRect = space.adjusted(0,valbase,0,0);
                if (rtl) {
                    headerRect.setLeft(option.rect.x() - headerWidth - 1);
                    valueRect.setRight(option.rect.x() - headerWidth - 1);
                } else {
                    headerRect.setRight(x + headerWidth + 1);
                    valueRect.setLeft(x + headerWidth + 1);
                }
                painter->setFont(fsmallbold);
                painter->drawText(headerRect, Qt::AlignLeading, subLine.first);
                painter->setFont(fsmall);
                painter->drawText(valueRect, Qt::AlignLeading, fsmallM.elidedText(subLine.second, Qt::ElideRight, valueRect.width()));
            } else {
                painter->setFont(fsmallbold);
                painter->drawText(space, Qt::AlignLeading, fsmallboldM.elidedText(subLine.first, Qt::ElideRight, space.width()));
            }
        } else {
            if (!subLine.second.isEmpty()) {
                painter->setFont(fsmall);
                painter->drawText(space, Qt::AlignLeading, fsmallM.elidedText(subLine.second, Qt::ElideRight, space.width()));
            }
        }

        y += sublineheight + 1;
    }
    painter->restore();
}
Example #4
0
void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
{
    Q_Q(QDockWidget);

    int fw = q->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, q);

    QRect geo = q->geometry();
    QRect titleRect = q->frameGeometry();
#ifdef Q_WS_MAC
    if ((features & QDockWidget::DockWidgetVerticalTitleBar)) {
        titleRect.setTop(geo.top());
        titleRect.setBottom(geo.bottom());
        titleRect.setRight(geo.left() - 1);
    } else
#endif
    {
        titleRect.setLeft(geo.left());
        titleRect.setRight(geo.right());
        titleRect.setBottom(geo.top() - 1);
        titleRect.adjust(0, fw, 0, 0);
    }

    switch (event->type()) {
        case QEvent::NonClientAreaMouseButtonPress:
            if (!titleRect.contains(event->globalPos()))
                break;
            if (state != 0)
                break;
            if (qobject_cast<QMainWindow*>(parent) == 0)
                break;
            if (isAnimating())
                break;
            initDrag(event->pos(), true);
            if (state == 0)
                break;
#ifdef Q_OS_WIN
            // On Windows, NCA mouse events don't contain modifier info
            state->ctrlDrag = GetKeyState(VK_CONTROL) & 0x8000;
#else
            state->ctrlDrag = event->modifiers() & Qt::ControlModifier;
#endif
            startDrag();
            break;
        case QEvent::NonClientAreaMouseMove:
            if (state == 0 || !state->dragging)
                break;
            if (state->nca) {
                endDrag();
            }
#ifdef Q_OS_MAC
            else { // workaround for lack of mouse-grab on Mac
                QMainWindowLayout *layout
                    = qobject_cast<QMainWindowLayout *>(q->parentWidget()->layout());
                Q_ASSERT(layout != 0);

                q->move(event->globalPos() - state->pressPos);
                if (!state->ctrlDrag)
                    layout->hover(state->widgetItem, event->globalPos());
            }
#endif
            break;
        case QEvent::NonClientAreaMouseButtonRelease:
#ifdef Q_OS_MAC
                        if (state)
                                endDrag();
#endif
                        break;
        case QEvent::NonClientAreaMouseButtonDblClick:
            _q_toggleTopLevel();
            break;
        default:
            break;
    }
}
Example #5
0
void Selection::emitChanged(const Region& region)
{
    Sheet * const sheet = d->activeSheet;
    if(!sheet) // no sheet no update needed
        return;
    Region extendedRegion;
    ConstIterator end(region.constEnd());
    for (ConstIterator it = region.constBegin(); it != end; ++it) {
        Element* element = *it;
        QRect area = element->rect();

        const ColumnFormat *col;
        //look at if column is hiding.
        //if it's hiding refreshing column+1 (or column -1 )
        int left = area.left();
        int right = area.right();
        int top = area.top();
        int bottom = area.bottom();

        // a merged cells is selected
        if (element->type() == Region::Element::Point) {
            Cell cell(sheet, left, top);
            if (cell.doesMergeCells()) {
                // extend to the merged region
                // prevents artefacts of the selection rectangle
                right += cell.mergedXCells();
                bottom += cell.mergedYCells();
            }
        }

        if (right < KS_colMax) {
            do {
                right++;
                col = sheet->columnFormat(right);
            } while (col->isHiddenOrFiltered() && right != KS_colMax);
        }
        if (left > 1) {
            do {
                left--;
                col = sheet->columnFormat(left);
            } while (col->isHiddenOrFiltered() && left != 1);
        }

        if (bottom < KS_rowMax) {
            do {
                bottom++;
                int lastHidden;
                if (sheet->rowFormats()->isHiddenOrFiltered(bottom, &lastHidden)) {
                    bottom = lastHidden;
                } else {
                    break;
                }
            } while (bottom != KS_rowMax);
        }

        if (top > 1) {
            do {
                top--;
                int firstHidden;
                if (sheet->rowFormats()->isHiddenOrFiltered(top, 0, &firstHidden)) {
                    top = firstHidden;
                } else {
                    break;
                }
            } while (top != 1);
        }

        area.setLeft(left);
        area.setRight(right);
        area.setTop(top);
        area.setBottom(bottom);

        extendedRegion.add(area, element->sheet());
    }

    const QList<Cell> masterCells = sheet->cellStorage()->masterCells(extendedRegion);
    for (int i = 0; i < masterCells.count(); ++i)
        extendedRegion.add(masterCells[i].cellPosition(), sheet);

    emit changed(extendedRegion);
}
Example #6
0
bool Conditions::isTrueFormula(const Cell &cell, const QString &formula, const QString &baseCellAddress) const
{
    Map* const map = cell.sheet()->map();
    ValueCalc *const calc = map->calc();
    Formula f(cell.sheet(), cell);
    f.setExpression('=' + formula);
    Region r(baseCellAddress, map, cell.sheet());
    if (r.isValid() && r.isSingular()) {
        QPoint basePoint = static_cast<Region::Point*>(*r.constBegin())->pos();
        QString newFormula('=');
        const Tokens tokens = f.tokens();
        for (int t = 0; t < tokens.count(); ++t) {
            const Token token = tokens[t];
            if (token.type() == Token::Cell || token.type() == Token::Range) {
                if (map->namedAreaManager()->contains(token.text())) {
                    newFormula.append(token.text());
                    continue;
                }
                const Region region(token.text(), map, cell.sheet());
                if (!region.isValid() || !region.isContiguous()) {
                    newFormula.append(token.text());
                    continue;
                }
                if (region.firstSheet() != r.firstSheet()) {
                    newFormula.append(token.text());
                    continue;
                }
                Region::Element* element = *region.constBegin();
                if (element->type() == Region::Element::Point) {
                    Region::Point* point = static_cast<Region::Point*>(element);
                    QPoint pos = point->pos();
                    if (!point->isRowFixed()) {
                        int delta = pos.y() - basePoint.y();
                        pos.setY(cell.row() + delta);
                    }
                    if (!point->isColumnFixed()) {
                        int delta = pos.x() - basePoint.x();
                        pos.setX(cell.column() + delta);
                    }
                    newFormula.append(Region(pos, cell.sheet()).name());
                } else {
                    Region::Range* range = static_cast<Region::Range*>(element);
                    QRect r = range->rect();
                    if (!range->isTopFixed()) {
                        int delta = r.top() - basePoint.y();
                        r.setTop(cell.row() + delta);
                    }
                    if (!range->isBottomFixed()) {
                        int delta = r.bottom() - basePoint.y();
                        r.setBottom(cell.row() + delta);
                    }
                    if (!range->isLeftFixed()) {
                        int delta = r.left() - basePoint.x();
                        r.setLeft(cell.column() + delta);
                    }
                    if (!range->isRightFixed()) {
                        int delta = r.right() - basePoint.x();
                        r.setRight(cell.column() + delta);
                    }
                    newFormula.append(Region(r, cell.sheet()).name());
                }
            } else {
                newFormula.append(token.text());
            }
        }
        f.setExpression(newFormula);
    }
    Value val = f.eval();
    return calc->conv()->asBoolean(val).asBoolean();
}
void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                 const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter,option,index);

    QFont aliasFont = option.font;
    QFont subFont   = option.font;
    QFont errorFont = subFont;
    QFont progressFont = subFont;

    progressFont.setPointSize( subFont.pointSize()-2);
    //font.setPixelSize(font.weight()+);
    aliasFont.setBold(true);
    aliasFont.setPointSize( subFont.pointSize()+2 );

    QFontMetrics subFm( subFont );
    QFontMetrics aliasFm( aliasFont );
    QFontMetrics progressFm( progressFont );

    int aliasMargin = aliasFm.height()/2;
    int margin = subFm.height()/4;

    if (index.data(AddButton).toBool()) {
        QSize hint = sizeHint(option, index);
        QStyleOptionButton opt;
        static_cast<QStyleOption&>(opt) = option;
        opt.state &= ~QStyle::State_Selected;
        opt.state |= QStyle::State_Raised;
        opt.text = addFolderText();
        opt.rect.setWidth(qMin(opt.rect.width(), hint.width()));
        opt.rect.adjust(0, aliasMargin, 0, -aliasMargin);
        QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
                , option.widget
#endif
            );
        return;
    }

    if (static_cast<const FolderStatusModel *>(index.model())->classify(index) != FolderStatusModel::RootFolder) {
        return;
    }
    painter->save();

    QIcon statusIcon      = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
    QString aliasText     = qvariant_cast<QString>(index.data(HeaderRole));
    QString pathText      = qvariant_cast<QString>(index.data(FolderPathRole));
    QString remotePath    = qvariant_cast<QString>(index.data(FolderSecondPathRole));
    QStringList errorTexts= qvariant_cast<QStringList>(index.data(FolderErrorMsg));

    int overallPercent    = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
    QString overallString = qvariant_cast<QString>(index.data(SyncProgressOverallString));
    QString itemString    = qvariant_cast<QString>(index.data(SyncProgressItemString));
    int warningCount      = qvariant_cast<int>(index.data(WarningCount));
    bool syncOngoing      = qvariant_cast<bool>(index.data(SyncRunning));

    // QString statusText = qvariant_cast<QString>(index.data(FolderStatus));
    bool syncEnabled = index.data(FolderAccountConnected).toBool();
    // QString syncStatus = syncEnabled? tr( "Enabled" ) : tr( "Disabled" );

    QRect iconRect = option.rect;
    QRect aliasRect = option.rect;

    iconRect.setLeft( option.rect.left() + aliasMargin );
    iconRect.setTop( iconRect.top() + aliasMargin ); // (iconRect.height()-iconsize.height())/2);

    // alias box
    aliasRect.setTop(aliasRect.top() + aliasMargin );
    aliasRect.setBottom(aliasRect.top() + aliasFm.height());
    aliasRect.setRight(aliasRect.right() - aliasMargin );

    // remote directory box
    QRect remotePathRect = aliasRect;
    remotePathRect.setTop(aliasRect.bottom() + margin );
    remotePathRect.setBottom(remotePathRect.top() + subFm.height());

    // local directory box
    QRect localPathRect = remotePathRect;
    localPathRect.setTop( remotePathRect.bottom() + margin );
    localPathRect.setBottom( localPathRect.top() + subFm.height());

    iconRect.setBottom(localPathRect.bottom());
    iconRect.setWidth(iconRect.height());

    int nextToIcon = iconRect.right()+aliasMargin;
    aliasRect.setLeft(nextToIcon);
    localPathRect.setLeft(nextToIcon);
    remotePathRect.setLeft(nextToIcon);

    int iconSize = iconRect.width();

    QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled );
    painter->drawPixmap(QPoint(iconRect.left(), iconRect.top()), pm);

    // only show the warning icon if the sync is running. Otherwise its
    // encoded in the status icon.
    if( warningCount > 0 && syncOngoing) {
        QRect warnRect;
        warnRect.setLeft(iconRect.left());
        warnRect.setTop(iconRect.bottom()-17);
        warnRect.setWidth(16);
        warnRect.setHeight(16);

        QIcon warnIcon(":/client/resources/warning");
        QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled );
        painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm );
    }

    auto palette = option.palette;

    if (qApp->style()->inherits("QWindowsVistaStyle")) {
        // Hack: Windows Vista's light blue is not contrasting enough for white

        // (code from QWindowsVistaStyle::drawControl for CE_ItemViewItem)
        palette.setColor(QPalette::All, QPalette::HighlightedText, palette.color(QPalette::Active, QPalette::Text));
        palette.setColor(QPalette::All, QPalette::Highlight, palette.base().color().darker(108));
    }


    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->setPen(palette.color(cg, QPalette::HighlightedText));
    } else {
        painter->setPen(palette.color(cg, QPalette::Text));
    }
    QString elidedAlias = aliasFm.elidedText(aliasText, Qt::ElideRight, aliasRect.width());
    painter->setFont(aliasFont);
    painter->drawText(aliasRect, elidedAlias);

    const bool showProgess = !overallString.isEmpty() || !itemString.isEmpty();
    if(!showProgess) {
        painter->setFont(subFont);
        QString elidedRemotePathText;

        if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
            elidedRemotePathText = subFm.elidedText(tr("Syncing selected files in your account with"),
                                                    Qt::ElideRight, remotePathRect.width());
        } else {
            elidedRemotePathText = subFm.elidedText(tr("Remote path: %1").arg(remotePath),
                                                    Qt::ElideMiddle, remotePathRect.width());
        }
        painter->drawText(remotePathRect, elidedRemotePathText);

        QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width());
        painter->drawText(localPathRect, elidedPathText);
    }

    // paint an error overlay if there is an error string

    int h = iconRect.bottom();
    if( !errorTexts.isEmpty() ) {
        h += aliasMargin;
        QRect errorRect = localPathRect;
        errorRect.setLeft( iconRect.left());
        errorRect.setTop( h );
        errorRect.setHeight(errorTexts.count() * subFm.height()+aliasMargin);
        errorRect.setRight( option.rect.right()-aliasMargin );

        painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
        painter->setPen( QColor(0xaa, 0xaa, 0xaa));
        painter->drawRoundedRect( errorRect, 4, 4 );

        painter->setPen( Qt::white );
        painter->setFont(errorFont);
        QRect errorTextRect = errorRect;
        errorTextRect.setLeft( errorTextRect.left()+aliasMargin );
        errorTextRect.setTop( errorTextRect.top()+aliasMargin/2 );

        int x = errorTextRect.left();
        int y = errorTextRect.top()+aliasMargin/2 + subFm.height()/2;

        foreach( QString eText, errorTexts ) {
            painter->drawText(x, y, subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width()-2*aliasMargin));
            y += subFm.height();
        }
Example #8
0
void
SourceDelegate::paintSource( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    painter->save();
    painter->setPen( Qt::black );
    QFont font = painter->font();
    font.setPointSize( TomahawkUtils::defaultFontSize() );
    painter->setFont( font );

    SourceTreeItem* item = index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >();
    SourcesModel::RowType type = static_cast< SourcesModel::RowType >( index.data( SourcesModel::SourceTreeItemTypeRole ).toInt() );

    const int iconRectVertMargin = m_margin / 4;
    const QRect iconRect = option.rect.adjusted( m_margin / 2 + m_margin / 4, iconRectVertMargin, -option.rect.width() + option.rect.height() + m_margin / 4, -iconRectVertMargin );
    QString name = index.data().toString();
    QPixmap avatar;
    int figWidth = 0;
    bool isPlaying = false;
    QString desc;
    QString tracks;

    bool shouldDrawDropHint = false;

    if ( type == SourcesModel::Source )
    {
        // If the user is about to drop a track on a peer
        QRect itemsRect = option.rect;
        QPoint cursorPos = m_parent->mapFromGlobal( QCursor::pos() );
        bool cursorInRect = itemsRect.contains( cursorPos );
        if ( cursorInRect && m_dropHoverIndex.isValid() && m_dropHoverIndex == index )
            shouldDrawDropHint = true;

        SourceItem* colItem = qobject_cast< SourceItem* >( item );
        Q_ASSERT( colItem );
        bool status = !( !colItem->source() || !colItem->source()->isOnline() );

        if ( colItem->source() && !colItem->source()->isLocal() )
        {
            if ( status )
            {
                tracks = QString::number( colItem->source()->trackCount() );
                if ( shouldDrawDropHint )
                    figWidth = iconRect.width();
                name = colItem->source()->friendlyName();
            }

            avatar = colItem->pixmap( iconRect.size() );
            isPlaying = !colItem->source()->currentTrack().isNull();
            desc = colItem->source()->textStatus();
            if ( colItem->source().isNull() )
                desc = tr( "All available tracks" );
        }
    }
    else if ( type == SourcesModel::ScriptCollection )
    {
        ScriptCollectionItem* scItem = qobject_cast< ScriptCollectionItem* >( item );
        Q_ASSERT( scItem );

        if ( !scItem->collection().isNull() )
        {
            int trackCount = scItem->collection()->trackCount();
            if ( trackCount >= 0 )
            {
                tracks = QString::number( trackCount );
                figWidth = painter->fontMetrics().width( tracks );
            }
            name = scItem->collection()->itemName();
        }

        avatar = scItem->icon().pixmap( iconRect.size() );
        desc = qobject_cast< Tomahawk::ScriptCollection* >( scItem->collection().data() )->description();
    }

    painter->setOpacity( 1.0 );
    painter->drawPixmap( iconRect, avatar );

    QRect textRect = option.rect.adjusted( iconRect.width() + m_margin, m_margin / 6 + m_margin / 32, -figWidth - ( figWidth ? m_margin : 0 ), 0 );
    QString text = painter->fontMetrics().elidedText( name, Qt::ElideRight, textRect.width() );
    {
        QTextOption to;
        to.setWrapMode( QTextOption::NoWrap );
        painter->setOpacity( 0.7 );
        painter->drawText( textRect, text, to );
    }

    textRect = option.rect.adjusted( iconRect.width() + m_margin, option.rect.height() / 2, -figWidth - ( figWidth ? m_margin : 0 ), -m_margin / 4 );

    if ( type == SourcesModel::Source )
    {
        SourceItem* colItem = qobject_cast< SourceItem* >( item );
        Q_ASSERT( colItem );

        bool privacyOn = TomahawkSettings::instance()->privateListeningMode() == TomahawkSettings::FullyPrivate;
        if ( !colItem->source().isNull() && colItem->source()->isLocal() && privacyOn )
        {
            QRect pmRect = textRect;
            pmRect.setRight( pmRect.left() + pmRect.height() );
            ActionCollection::instance()->getAction( "togglePrivacy" )->icon().paint( painter, pmRect );
            textRect.adjust( pmRect.width() + m_margin / 8, 0, 0, 0 );
        }
        if ( ( isPlaying || ( !colItem->source().isNull() && colItem->source()->isLocal() ) ) && !shouldDrawDropHint )
        {
            // Show a listen icon
            TomahawkUtils::ImageType listenAlongPixmap = TomahawkUtils::Invalid;
            TomahawkUtils::ImageType realtimeListeningAlongPixmap = TomahawkUtils::Invalid;
            if ( index.data( SourcesModel::LatchedOnRole ).toBool() )
            {
                // Currently listening along
                listenAlongPixmap = TomahawkUtils::HeadphonesOn;
                if ( !colItem->source()->isLocal() )
                {
                    realtimeListeningAlongPixmap =
                        colItem->source()->playlistInterface()->latchMode() == Tomahawk::PlaylistModes::RealTime ?
                            TomahawkUtils::PadlockClosed : TomahawkUtils::PadlockOpen;
                }
            }
            else if ( !colItem->source()->isLocal() )
            {
                listenAlongPixmap = TomahawkUtils::HeadphonesOff;
            }

            if ( listenAlongPixmap != TomahawkUtils::Invalid )
            {
                QRect pmRect = textRect;
                pmRect.setRight( pmRect.left() + pmRect.height() );
                painter->drawPixmap( pmRect, TomahawkUtils::defaultPixmap( listenAlongPixmap, TomahawkUtils::Original, pmRect.size() ) );
                textRect.adjust( pmRect.width() + m_margin / 8, 0, 0, 0 );

                m_headphoneRects[ index ] = pmRect;
            }
            else
                m_headphoneRects.remove( index );

            if ( realtimeListeningAlongPixmap != TomahawkUtils::Invalid )
            {
                QRect pmRect = textRect;
                pmRect.setRight( pmRect.left() + pmRect.height() );
                painter->drawPixmap( pmRect, TomahawkUtils::defaultPixmap( realtimeListeningAlongPixmap, TomahawkUtils::Original, pmRect.size() ) );
                textRect.adjust( pmRect.width() + m_margin / 8, 0, 0, 0 );

                m_lockRects[ index ] = pmRect;
            }
            else
                m_lockRects.remove( index );
        }
    }

    painter->save();
    if ( m_trackHovered == index )
    {
        QFont font = painter->font();
        font.setUnderline( true );
        painter->setFont( font );
    }
    textRect.adjust( 0, 0, 0, m_margin / 16 );

    if ( shouldDrawDropHint )
    {
        desc = tr( "Drop to send tracks" );
    }

    text = painter->fontMetrics().elidedText( desc, Qt::ElideRight, textRect.width() - m_margin / 4 );
    {
        QTextOption to( Qt::AlignVCenter );
        to.setWrapMode( QTextOption::NoWrap );

        painter->setOpacity( 0.4 );
        painter->drawText( textRect, text, to );
    }
    painter->restore();

    bool shouldPaintTrackCount = false;
    if ( type == SourcesModel::Source )
    {
        SourceItem* colItem = qobject_cast< SourceItem* >( item );
        Q_ASSERT( colItem );

        if ( colItem->source() && colItem->source()->currentTrack() && colItem->source()->state() == Tomahawk::SYNCED )
            m_trackRects[ index ] = textRect.adjusted( 0, 0, -textRect.width() + painter->fontMetrics().width( text ), 0 );
        else
            m_trackRects.remove( index );
    }
    else if ( type == SourcesModel::ScriptCollection )
    {
        if ( !tracks.isEmpty() )
            shouldPaintTrackCount = true;
    }

    if ( shouldPaintTrackCount || shouldDrawDropHint )
    {
        if ( shouldDrawDropHint )
        {
            const QRect figRect = option.rect.adjusted( option.rect.width() - figWidth - iconRectVertMargin, iconRectVertMargin, -iconRectVertMargin, -iconRectVertMargin );
            painter->drawPixmap( figRect, TomahawkUtils::defaultPixmap( TomahawkUtils::Inbox, TomahawkUtils::Original, figRect.size() ) );
        }
        else
        {
            const QRect figRect = option.rect.adjusted( option.rect.width() - figWidth - m_margin / 2, 0, -m_margin / 2, 0 );
            painter->drawText( figRect, tracks, QTextOption( Qt::AlignVCenter | Qt::AlignRight ) );
        }
    }

    painter->restore();
}
void RegionGrabber::mouseMoveEvent( QMouseEvent* e )
{
    bool shouldShowHelp = !helpTextRect.contains( e->pos() );
    if (shouldShowHelp != showHelp) {
        showHelp = shouldShowHelp;
        update();
    }

    if ( mouseDown )
    {
        if ( newSelection )
        {
            QPoint p = e->pos();
            QRect r = rect();
            selection = normalizeSelection(QRect( dragStartPoint, limitPointToRect( p, r ) ));
        }
        else if ( mouseOverHandle == 0 ) // moving the whole selection
        {
            QRect r = rect().normalized(), s = selectionBeforeDrag.normalized();
            QPoint p = s.topLeft() + e->pos() - dragStartPoint;
            r.setBottomRight( r.bottomRight() - QPoint( s.width(), s.height() ) + QPoint( 1, 1 ) );
            if ( !r.isNull() && r.isValid() )
                selection.moveTo( limitPointToRect( p, r ) );
        }
        else // dragging a handle
        {
            QRect r = selectionBeforeDrag;
            QPoint offset = e->pos() - dragStartPoint;

            if ( mouseOverHandle == &TLHandle || mouseOverHandle == &THandle
                    || mouseOverHandle == &TRHandle ) // dragging one of the top handles
            {
                r.setTop( r.top() + offset.y() );
            }

            if ( mouseOverHandle == &TLHandle || mouseOverHandle == &LHandle
                    || mouseOverHandle == &BLHandle ) // dragging one of the left handles
            {
                r.setLeft( r.left() + offset.x() );
            }

            if ( mouseOverHandle == &BLHandle || mouseOverHandle == &BHandle
                    || mouseOverHandle == &BRHandle ) // dragging one of the bottom handles
            {
                r.setBottom( r.bottom() + offset.y() );
            }

            if ( mouseOverHandle == &TRHandle || mouseOverHandle == &RHandle
                    || mouseOverHandle == &BRHandle ) // dragging one of the right handles
            {
                r.setRight( r.right() + offset.x() );
            }
            r.setTopLeft( limitPointToRect( r.topLeft(), rect() ) );
            r.setBottomRight( limitPointToRect( r.bottomRight(), rect() ) );
            selection = normalizeSelection(r);
        }
        update();
    }
    else
    {
        if ( selection.isNull() )
            return;
        bool found = false;
        foreach( QRect* r, handles )
        {
            if ( r->contains( e->pos() ) )
            {
                mouseOverHandle = r;
                found = true;
                break;
            }
        }
        if ( !found )
        {
            mouseOverHandle = 0;
            if ( selection.contains( e->pos() ) )
                setCursor( Qt::OpenHandCursor );
            else
                setCursor( Qt::CrossCursor );
        }
        else
        {
            if ( mouseOverHandle == &TLHandle || mouseOverHandle == &BRHandle )
                setCursor( Qt::SizeFDiagCursor );
            if ( mouseOverHandle == &TRHandle || mouseOverHandle == &BLHandle )
                setCursor( Qt::SizeBDiagCursor );
            if ( mouseOverHandle == &LHandle || mouseOverHandle == &RHandle )
                setCursor( Qt::SizeHorCursor );
            if ( mouseOverHandle == &THandle || mouseOverHandle == &BHandle )
                setCursor( Qt::SizeVerCursor );
        }
    }
}
Example #10
0
/*!
   Draw a text into a rectangle

   \param painter Painter
   \param rect Rectangle
*/
void QwtText::draw(QPainter *painter, const QRect &rect) const
{
    if ( d_data->paintAttributes & PaintBackground )
    {
        if ( d_data->backgroundPen != Qt::NoPen || 
            d_data->backgroundBrush != Qt::NoBrush )
        {
            painter->save();
            painter->setPen(QwtPainter::scaledPen(d_data->backgroundPen));
            painter->setBrush(d_data->backgroundBrush);
#if QT_VERSION < 0x040000
            QwtPainter::drawRect(painter, rect);
#else
            const QRect r(rect.x(), rect.y(), 
                rect.width() - 1, rect.height() - 1);
            QwtPainter::drawRect(painter, r);
#endif
            painter->restore();
        }
    }

    painter->save();

    if ( d_data->paintAttributes & PaintUsingTextFont )
    {
        painter->setFont(d_data->font);
    }

    if ( d_data->paintAttributes & PaintUsingTextColor )
    {
        if ( d_data->color.isValid() )
            painter->setPen(d_data->color);
    }

    QRect expandedRect = rect;
    if ( d_data->layoutAttributes & MinimumLayout )
    {
#if QT_VERSION < 0x040000
        const QFont font(painter->font());
#else
        // We want to calculate in screen metrics. So
        // we need a font that uses screen metrics

        const QFont font(painter->font(), QApplication::desktop());
#endif

        int left, right, top, bottom;
        d_data->textEngine->textMargins(
            font, d_data->text,
            left, right, top, bottom);

        const QwtMetricsMap map = QwtPainter::metricsMap();
        left = map.screenToLayoutX(left);
        right = map.screenToLayoutX(right);
        top = map.screenToLayoutY(top);
        bottom = map.screenToLayoutY(bottom);

        expandedRect.setTop(rect.top() - top);
        expandedRect.setBottom(rect.bottom() + bottom);
        expandedRect.setLeft(rect.left() - left);
        expandedRect.setRight(rect.right() + right);
    }

    d_data->textEngine->draw(painter, expandedRect, 
        d_data->renderFlags, d_data->text);

    painter->restore();
}
Example #11
0
void BakaEngine::FitWindow(int percent, bool msg)
{
    if(window->isFullScreen() || window->isMaximized() || !window->ui->menuFit_Window->isEnabled())
        return;

    mpv->LoadVideoParams();

    const Mpv::VideoParams &vG = mpv->getFileInfo().video_params; // video geometry
    QRect mG = window->ui->mpvFrame->geometry(),                  // mpv geometry
          wfG = window->frameGeometry(),                          // frame geometry of window (window geometry + window frame)
          wG = window->geometry(),                                // window geometry
          aG = qApp->desktop()->availableGeometry(wfG.center());  // available geometry of the screen we're in--(geometry not including the taskbar)

    double a, // aspect ratio
           w, // width of vid we want
           h; // height of vid we want

    // obtain natural video aspect ratio
    if(vG.width == 0 || vG.height == 0) // width/height are 0 when there is no output
        return;
    if(vG.dwidth == 0 || vG.dheight == 0) // dwidth/height are 0 on load
        a = double(vG.width)/vG.height; // use video width and height for aspect ratio
    else
        a = double(vG.dwidth)/vG.dheight; // use display width and height for aspect ratio

    // calculate resulting display:
    if(percent == 0) // fit to window
    {
        // set our current mpv frame dimensions
        w = mG.width();
        h = mG.height();

        double cmp = w/h - a, // comparison
               eps = 0.01;  // epsilon (deal with rounding errors) we consider -eps < 0 < eps ==> 0

        if(cmp > eps) // too wide
            w = h * a; // calculate width based on the correct height
        else if(cmp < -eps) // too long
            h = w / a; // calculate height based on the correct width
    }
    else // fit into desired dimensions
    {
        double scale = percent / 100.0; // get scale

        w = vG.width * scale;  // get scaled width
        h = vG.height * scale; // get scaled height
    }

    double dW = w + (wfG.width() - mG.width()),   // calculate display width of the window
           dH = h + (wfG.height() - mG.height()); // calculate display height of the window

    if(dW > aG.width()) // if the width is bigger than the available area
    {
        dW = aG.width(); // set the width equal to the available area
        w = dW - (wfG.width() - mG.width());    // calculate the width
        h = w / a;                              // calculate height
        dH = h + (wfG.height() - mG.height());  // calculate new display height
    }
    if(dH > aG.height()) // if the height is bigger than the available area
    {
        dH = aG.height(); // set the height equal to the available area
        h = dH - (wfG.height() - mG.height()); // calculate the height
        w = h * a;                             // calculate the width accordingly
        dW = w + (wfG.width() - mG.width());   // calculate new display width
    }

    // get the centered rectangle we want
    QRect rect = QStyle::alignedRect(Qt::LeftToRight,
                                     Qt::AlignCenter,
                                     QSize(dW,
                                           dH),
                                     percent == 0 ? wfG : aG); // center in window (autofit) or on our screen

    // adjust the rect to compensate for the frame
    rect.setLeft(rect.left() + (wG.left() - wfG.left()));
    rect.setTop(rect.top() + (wG.top() - wfG.top()));
    rect.setRight(rect.right() - (wfG.right() - wG.right()));
    rect.setBottom(rect.bottom() - (wfG.bottom() - wG.bottom()));

    // finally set the geometry of the window
    window->setGeometry(rect);

    // note: the above block is required because there is no setFrameGeometry function

    if(msg)
        mpv->ShowText(tr("Fit Window: %0").arg(percent == 0 ? tr("To Current Size") : (QString::number(percent)+"%")));
}
Example #12
0
void PlaylistDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    QStyledItemDelegate::paint(painter, option, index);
    const QImage image = m_cache->image(index.data(m_thumbnailRole).toString(), QSize(80, 60));
    
    QRect imageRect = option.rect;
    imageRect.setLeft(imageRect.left() + 8);
    imageRect.setTop(imageRect.top() + 8);
    imageRect.setWidth(80);
    imageRect.setHeight(60);
    
    painter->fillRect(imageRect, Qt::black);
    drawCenteredImage(painter, imageRect, image);
    
    const int count = index.data(m_videoCountRole).toInt();
    
    if (count != -1) {
        QFont font;
        QRect durationRect = imageRect;
        const int durationHeight = durationRect.height() / 4;
        font.setPixelSize(durationHeight);        
        durationRect.setTop(durationRect.bottom() - (durationHeight));
        
        painter->save();
        painter->setOpacity(0.8);
        painter->fillRect(durationRect, Qt::black);
        painter->setFont(font);
        painter->setOpacity(1);
        painter->setPen(Qt::white);
        painter->drawText(durationRect, Qt::AlignCenter, count > 0 ? tr("%1 videos").arg(count) : tr("No videos"));
        painter->restore();
    }
    
    painter->save();
    painter->setPen(QApplication::palette().color(QPalette::Mid));
    painter->drawRect(imageRect);
    painter->setPen(QApplication::palette().color(QPalette::Text));
    
    QRect textRect = option.rect;
    textRect.setLeft(imageRect.right() + 8);
    textRect.setRight(textRect.right() - 8);
    textRect.setTop(textRect.top() + 8);
    textRect.setBottom(textRect.bottom() - 8);
    
    QString subTitle;
    const QString username = index.data(m_usernameRole).toString();
    const QString date = index.data(m_dateRole).toString();
    
    if (!username.isEmpty()) {
        subTitle.append(QString("%1 %2").arg(tr("by")).arg(username));
    }
    
    if (!date.isEmpty()) {
        if (!username.isEmpty()) {
            subTitle.append(QString(" %1 ").arg(tr("on")));
        }
        
        subTitle.append(date);
    }
    
    if (!subTitle.isEmpty()) {
        painter->drawText(textRect, Qt::AlignLeft | Qt::AlignTop,
                          painter->fontMetrics().elidedText(index.data(m_titleRole).toString(),
                          Qt::ElideRight, textRect.width()));
        painter->setPen(QApplication::palette().color(QPalette::Mid));
        painter->drawText(textRect, Qt::AlignLeft | Qt::AlignBottom,
                          painter->fontMetrics().elidedText(subTitle, Qt::ElideRight, textRect.width()));
    }
    else {                
        painter->drawText(textRect, Qt::AlignVCenter | Qt::TextWordWrap, index.data(m_titleRole).toString());
    }
    
    painter->restore();
}
Example #13
0
void TabBarWidgetMacStyle::tabLayout(const QStyleOptionTab *pOption,
                                     const QWidget *pWidget, QRect *pTextRect,
                                     QRect *pIconRect) const
{
    // Compute our tab layout
    // Note: adapted from QCommonStylePrivate::tabLayout()...

    Q_ASSERT(pTextRect);
    Q_ASSERT(pIconRect);

    QRect textRect = pOption->rect;
    bool verticalTab =    (pOption->shape == QTabBar::RoundedWest)
                       || (pOption->shape == QTabBar::RoundedEast)
                       || (pOption->shape == QTabBar::TriangularWest)
                       || (pOption->shape == QTabBar::TriangularEast);

    if (verticalTab) {
        textRect.setRect(0, 0, textRect.height(), textRect.width());
    }

    if (!pOption->leftButtonSize.isEmpty()) {
        textRect.adjust(-4, 0, 0, 0);
    }

    int horizontalShift = pixelMetric(QStyle::PM_TabBarTabShiftHorizontal, pOption, pWidget);
    int verticalShift = pixelMetric(QStyle::PM_TabBarTabShiftVertical, pOption, pWidget);
    int horizontalPadding = pixelMetric(QStyle::PM_TabBarTabHSpace, pOption, pWidget)/2;
    int verticalPadding = pixelMetric(QStyle::PM_TabBarTabVSpace, pOption, pWidget)/2;

    if (   (pOption->shape == QTabBar::RoundedSouth)
        || (pOption->shape == QTabBar::TriangularSouth)) {
        verticalShift = -verticalShift;
    }

    textRect.adjust(horizontalPadding, verticalShift-verticalPadding,
                    horizontalShift-horizontalPadding, verticalPadding);

    if ((pOption->state & QStyle::State_Selected) != 0) {
        textRect.setTop(textRect.top()-verticalShift);
        textRect.setRight(textRect.right()-horizontalShift);
    }

    if (!pOption->leftButtonSize.isEmpty()) {
        textRect.setLeft( textRect.left()
                         +(verticalTab?
                               pOption->leftButtonSize.height():
                               pOption->leftButtonSize.width()));
    }

    if (!pOption->rightButtonSize.isEmpty()) {
        textRect.setRight( textRect.right()
                          -(verticalTab?
                                pOption->rightButtonSize.height():
                                pOption->rightButtonSize.width()));
    }

    if (!pOption->icon.isNull()) {
        QSize iconSize = pOption->iconSize;

        if (!iconSize.isValid()) {
            int iconExtent = pixelMetric(QStyle::PM_SmallIconSize);

            iconSize = QSize(iconExtent, iconExtent);
        }

        QSize tabIconSize = pOption->icon.actualSize(iconSize,
                                                     ((pOption->state & QStyle::State_Enabled) != 0)?
                                                         QIcon::Normal:
                                                         QIcon::Disabled,
                                                     ((pOption->state & QStyle::State_Selected) != 0)?
                                                         QIcon::On:
                                                         QIcon::Off);

        tabIconSize = QSize(qMin(tabIconSize.width(), iconSize.width()),
                            qMin(tabIconSize.height(), iconSize.height()));

        *pIconRect = QRect(textRect.left(), textRect.center().y()-tabIconSize.height()/2,
                           tabIconSize.width(), tabIconSize.height());

        if (!verticalTab) {
            *pIconRect = visualRect(pOption->direction, pOption->rect, *pIconRect);
        }

        textRect.setLeft(textRect.left()+tabIconSize.width()+4);
    }

    if (!verticalTab) {
        textRect = visualRect(pOption->direction, pOption->rect, textRect);
    }

    *pTextRect = textRect;
}
void QFontFamilyDelegate::paint(QPainter *painter,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    QString text = index.data(Qt::DisplayRole).toString();
    QFont font(option.font);
    font.setPointSize(QFontInfo(font).pointSize() * 3 / 2);
    QFont font2 = font;
    font2.setFamily(text);

    bool hasLatin;
    QFontDatabase::WritingSystem system = writingSystemForFont(font2, &hasLatin);
    if (hasLatin)
        font = font2;

    QRect r = option.rect;

    if (option.state & QStyle::State_Selected) {
        painter->save();
        painter->setBrush(option.palette.highlight());
        painter->setPen(Qt::NoPen);
        painter->drawRect(option.rect);
        painter->setPen(QPen(option.palette.highlightedText(), 0));
    }

    const QIcon *icon = &bitmap;
    if (QFontDatabase().isSmoothlyScalable(text)) {
        icon = &truetype;
    }
    QSize actualSize = icon->actualSize(r.size());

    icon->paint(painter, r, Qt::AlignLeft|Qt::AlignVCenter);
    if (option.direction == Qt::RightToLeft)
        r.setRight(r.right() - actualSize.width() - 4);
    else
        r.setLeft(r.left() + actualSize.width() + 4);

    QFont old = painter->font();
    painter->setFont(font);

    // If the ascent of the font is larger than the height of the rect,
    // we will clip the text, so it's better to align the tight bounding rect in this case
    // This is specifically for fonts where the ascent is very large compared to
    // the descent, like certain of the Stix family.
    QFontMetricsF fontMetrics(font);
    if (fontMetrics.ascent() > r.height()) {
        QRectF tbr = fontMetrics.tightBoundingRect(text);
        painter->drawText(r.x(), r.y() + (r.height() + tbr.height()) / 2.0, text);
    } else {
        painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, text);
    }

    if (writingSystem != QFontDatabase::Any)
        system = writingSystem;

    if (system != QFontDatabase::Any) {
        int w = painter->fontMetrics().width(text + QLatin1String("  "));
        painter->setFont(font2);
        QString sample = QFontDatabase().writingSystemSample(system);
        if (option.direction == Qt::RightToLeft)
            r.setRight(r.right() - w);
        else
            r.setLeft(r.left() + w);
        painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, sample);
    }
    painter->setFont(old);

    if (option.state & QStyle::State_Selected)
        painter->restore();

}
Example #15
0
void View::setYPos(int y)
      {
      int delta  = ypos - y;         // -  -> shift up
      ypos  = y;
      
      #ifdef VIEW_USE_DOUBLE_BUFFERING
      if (pm.isNull())
            return;
      if (!pmValid) {
            //printf("View::setYPos !pmValid y:%d height:%d delta:%d\n", y, height(), delta);
            
            redraw();
            return;
            }
      
      int w = width();
      int h = height();
      
      QRect r;
      if (delta >= h || delta <= -h)
            r = QRect(0, 0, w, h);
      else if (delta < 0) {   // shift up
            //bitBlt(&pm,  0, 0, &pm, 0, -delta, w, h + delta, CopyROP, true);
            QPainter p(&pm);
            p.drawPixmap(0, 0, pm, 0, -delta, w, h + delta);
            r = QRect(0, h + delta, w, -delta);
            }
      else {                  // shift down
            //bitBlt(&pm,  0, delta, &pm, 0, 0, w, h-delta, CopyROP, true);
            QPainter p(&pm);
            p.drawPixmap(0, delta, pm, 0, 0, w, h-delta);
            r = QRect(0, 0, w, delta);
            }
      QRect olr = overlayRect();
      QRect olr1(olr);
      olr1.translate(0, delta);

      r |= olr;
      r |= olr1;

      //printf("View::setYPos paint delta:%d r.x:%d r.y:%d r.w:%d r.h:%d\n", delta, r.x(), r.y(), r.width(), r.height());  
      
      paint(r);
      update();
      
      #else
      scroll(0, delta);
      QRect olr = overlayRect();
      // Is there an overlay?
      if(!olr.isNull())
      {
        // Are we shifting down (moving up)?
        if(delta >= 0)
        {
          // Translate not good - need to set y to delta.
          //olr.translate(0, delta);
          olr.setY(delta);
          olr.setHeight(olr.y() + olr.height() + delta);
        }
        else
        // We are shifting up (moving down).
        {
          // Translate not good - need to limit y to 0.
          //olr.translate(0, delta);
          olr.setY(olr.y() + delta);
        }
        
        if(olr.x() < 0)
          olr.setX(0);
        if(olr.right() > width())
          olr.setRight(width());
        
        if(olr.y() < 0)
          olr.setY(0);
        if(olr.bottom() > height())
          olr.setBottom(height());
        
        //printf("scroll Y update: x:%d y:%d w:%d h:%d\n", olr.x(), olr.y(), olr.width(), olr.height()); 
        update(olr);
      }  
      #endif
      }
void PlaylistItemDelegate::paintBody(QPainter *painter,
                                     const QStyleOptionViewItem &option,
                                     const QModelIndex &index) const {
    const bool isSelected = option.state & QStyle::State_Selected;
    if (isSelected)
        QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);

    painter->save();
    painter->translate(option.rect.topLeft());

    QRect line(0, 0, option.rect.width(), option.rect.height());
    if (downloadInfo) line.setWidth(line.width() / 2);

    const bool isActive = index.data(ActiveTrackRole).toBool();

    // get the video metadata
    const Video *video = index.data(VideoRole).value<VideoPointer>().data();

    // draw the "current track" highlight underneath the text
    if (isActive && !isSelected) paintActiveOverlay(painter, option, line);

    // thumb
    const QPixmap &thumb = video->getThumbnail();
    if (!thumb.isNull()) {
        painter->drawPixmap(0, 0, thumb);
        if (video->getDuration() > 0) drawTime(painter, video->getFormattedDuration(), line);
    }

    const bool thumbsOnly = line.width() <= thumbWidth + 60;
    const bool isHovered = index.data(HoveredItemRole).toBool();

    // play icon overlayed on the thumb
    bool needPlayIcon = isActive;
    if (thumbsOnly) needPlayIcon = needPlayIcon && !isHovered;
    if (needPlayIcon) painter->drawPixmap(0, 0, playIcon);

    if (!thumbsOnly) {
        // text color
        if (isSelected)
            painter->setPen(QPen(option.palette.highlightedText(), 0));
        else
            painter->setPen(QPen(option.palette.text(), 0));

        // title
        QStringRef title(&video->getTitle());
        QString elidedTitle = video->getTitle();
        static const int titleFlags = Qt::AlignTop | Qt::TextWordWrap;
        QRect textBox = line.adjusted(padding + thumbWidth, padding, -padding, 0);
        textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
        while (textBox.height() > 55 && elidedTitle.length() > 10) {
#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
            title = title.left(title.length() - 1);
#elif QT_VERSION < QT_VERSION_CHECK(5, 8, 0)
            title.truncate(title.length() - 1);
#else
            title.chop(1);
#endif
            elidedTitle = title.trimmed() + QStringLiteral("…");
            textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
        }
        painter->drawText(textBox, titleFlags, elidedTitle);

        painter->setFont(smallerFont);
        painter->setOpacity(.5);
        QFontMetrics fontMetrics = painter->fontMetrics();
        static const int flags = Qt::AlignLeft | Qt::AlignTop;

        // published date
        const QString &published = video->getFormattedPublished();
        QSize textSize(fontMetrics.size(Qt::TextSingleLine, published));
        QPoint textPoint(padding + thumbWidth, padding * 2 + textBox.height());
        textBox = QRect(textPoint, textSize);
        painter->drawText(textBox, flags, published);

        bool elided = false;

        // author
        if (!listView || listView->isClickableAuthors()) {
            bool authorHovered = isHovered && index.data(AuthorHoveredRole).toBool();

            painter->save();
            painter->setFont(smallerBoldFont);
            if (!isSelected) {
                if (authorHovered)
                    painter->setPen(QPen(option.palette.brush(QPalette::Highlight), 0));
            }
            const QString &author = video->getChannelTitle();
            textPoint.setX(textBox.right() + padding);
            textSize = QSize(painter->fontMetrics().size(Qt::TextSingleLine, author));
            textBox = QRect(textPoint, textSize);
            authorRects.insert(index.row(), textBox);
            if (textBox.right() > line.width() - padding) {
                textBox.setRight(line.width());
                elided = drawElidedText(painter, textBox, flags, author);
            } else {
                painter->drawText(textBox, flags, author);
            }
            painter->restore();
        }

        // view count
        if (video->getViewCount() > 0) {
            const QString &viewCount = video->getFormattedViewCount();
            textPoint.setX(textBox.right() + padding);
            textSize = QSize(fontMetrics.size(Qt::TextSingleLine, viewCount));
            if (elided || textPoint.x() + textSize.width() > line.width() - padding) {
                textPoint.setX(thumbWidth + padding);
                textPoint.setY(textPoint.y() + textSize.height() + padding);
            }
            textBox = QRect(textPoint, textSize);
            if (textBox.bottom() <= line.height()) {
                painter->drawText(textBox, flags, viewCount);
            }
        }

        if (downloadInfo) {
            const QString &def = VideoDefinition::forCode(video->getDefinitionCode()).getName();
            textPoint.setX(textBox.right() + padding);
            textSize = QSize(fontMetrics.size(Qt::TextSingleLine, def));
            textBox = QRect(textPoint, textSize);
            painter->drawText(textBox, flags, def);
        }

    } else {
        // thumbs only
        if (isHovered) {
            painter->setFont(smallerFont);
            painter->setPen(Qt::white);
            QStringRef title(&video->getTitle());
            QString elidedTitle = video->getTitle();
            static const int titleFlags = Qt::AlignTop | Qt::TextWordWrap;
            QRect textBox(padding, padding, thumbWidth - padding * 2, thumbHeight - padding * 2);
            textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
            while (textBox.height() > 55 && elidedTitle.length() > 10) {
#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
                title = title.left(title.length() - 1);
#elif QT_VERSION < QT_VERSION_CHECK(5, 8, 0)
                title.truncate(title.length() - 1);
#else
                title.chop(1);
#endif
                elidedTitle = title.trimmed() + QStringLiteral("…");
                textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
            }
            painter->fillRect(QRect(0, 0, thumbWidth, textBox.height() + padding * 2),
                              QColor(0, 0, 0, 128));
            painter->drawText(textBox, titleFlags, elidedTitle);
        }
    }

    painter->restore();

    if (downloadInfo) paintDownloadInfo(painter, option, index);
}
Example #17
0
// --------------------------------------------------
void ctkSearchBox::paintEvent(QPaintEvent * event)
{
  Q_D(ctkSearchBox);

  // Draw the line edit with text.
  // Text has already been shifted to the right (in resizeEvent()) to leave
  // space for the search icon.
  this->Superclass::paintEvent(event);

  QPainter p(this);

  QRect cRect = d->clearRect();
  QRect sRect = d->showSearchIcon ? d->searchRect() : QRect();

#if QT_VERSION >= 0x040700
  QRect r = rect();
  QPalette pal = palette();

  QStyleOptionFrameV2 panel;
  initStyleOption(&panel);
  r = this->style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
  r.setX(r.x() + this->textMargins().left());
  r.setY(r.y() + this->textMargins().top());
  r.setRight(r.right() - this->textMargins().right());
  r.setBottom(r.bottom() - this->textMargins().bottom());
  p.setClipRect(r);

  QFontMetrics fm = fontMetrics();
  Qt::Alignment va = QStyle::visualAlignment(this->layoutDirection(),
                                             QFlag(this->alignment()));
  int vscroll = 0;
  const int verticalMargin = 1;
  const int horizontalMargin = 2;
  switch (va & Qt::AlignVertical_Mask) {
   case Qt::AlignBottom:
       vscroll = r.y() + r.height() - fm.height() - verticalMargin;
       break;
   case Qt::AlignTop:
       vscroll = r.y() + verticalMargin;
       break;
   default:
       //center
       vscroll = r.y() + (r.height() - fm.height() + 1) / 2;
       break;
  }
  QRect lineRect(r.x() + horizontalMargin, vscroll,
                 r.width() - 2*horizontalMargin, fm.height());

  int minLB = qMax(0, -fm.minLeftBearing());

  if (this->text().isEmpty())
    {
    if (!this->hasFocus() && !this->placeholderText().isEmpty())
      {
      QColor col = pal.text().color();
      col.setAlpha(128);
      QPen oldpen = p.pen();
      p.setPen(col);
      lineRect.adjust(minLB, 0, 0, 0);
      QString elidedText = fm.elidedText(this->placeholderText(), Qt::ElideRight, lineRect.width());
      p.drawText(lineRect, va, elidedText);
      p.setPen(oldpen);
      }
    }
  p.setClipRect(this->rect());
#endif

  // Draw clearIcon
  if (!d->hideClearIcon)
    {
    QPixmap closePixmap = d->clearIcon.pixmap(cRect.size(),this->isEnabled() ? QIcon::Normal : QIcon::Disabled);
    this->style()->drawItemPixmap(&p, cRect, Qt::AlignCenter, closePixmap);
    }

  // Draw searchIcon
  if (d->showSearchIcon)
    {
    QPixmap searchPixmap = d->searchIcon.pixmap(sRect.size(), this->isEnabled() ? QIcon::Normal : QIcon::Disabled);
    this->style()->drawItemPixmap(&p, sRect, Qt::AlignCenter, searchPixmap);
    }
}
Example #18
0
void Waveform::paintEvent(QPaintEvent * /*event*/)
{
    QPainter painter(this);

    painter.fillRect(rect(), Qt::black);

    if (m_active) {
        WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent"
                             << "windowPosition" << m_windowPosition
                             << "windowLength" << m_windowLength;
        qint64 pos = m_windowPosition;
        const qint64 windowEnd = m_windowPosition + m_windowLength;
        int destLeft = 0;
        int destRight = 0;
        while (pos < windowEnd) {
            const TilePoint point = tilePoint(pos);
            WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "pos" << pos
                                 << "tileIndex" << point.index
                                 << "positionOffset" << point.positionOffset
                                 << "pixelOffset" << point.pixelOffset;

            if (point.index != NullIndex) {
                const Tile &tile = m_tiles[point.index];
                if (tile.painted) {
                    const qint64 sectionLength = qMin((m_tileLength - point.positionOffset),
                                                     (windowEnd - pos));
                    Q_ASSERT(sectionLength > 0);

                    const int sourceRight = tilePixelOffset(point.positionOffset + sectionLength);
                    destRight = windowPixelOffset(pos - m_windowPosition + sectionLength);

                    QRect destRect = rect();
                    destRect.setLeft(destLeft);
                    destRect.setRight(destRight);

                    QRect sourceRect(QPoint(), m_pixmapSize);
                    sourceRect.setLeft(point.pixelOffset);
                    sourceRect.setRight(sourceRight);

                    WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "tileIndex" << point.index
                                         << "source" << point.pixelOffset << sourceRight
                                         << "dest" << destLeft << destRight;

                    painter.drawPixmap(destRect, *tile.pixmap, sourceRect);

                    destLeft = destRight;

                    if (point.index < m_tiles.count()) {
                        pos = tilePosition(point.index + 1);
                        WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "pos ->" << pos;
                    } else {
                        // Reached end of tile array
                        WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "reached end of tile array";
                        break;
                    }
                } else {
                    // Passed last tile which is painted
                    WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "tile" << point.index << "not painted";
                    break;
                }
            } else {
                // pos is past end of tile array
                WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "pos" << pos << "past end of tile array";
                break;
            }
        }

        WAVEFORM_PAINT_DEBUG << "Waveform::paintEvent" << "final pos" << pos << "final x" << destRight;
    }
}
Example #19
0
void QWaylandMaterialDecoration::paint(QPaintDevice *device)
{
    QRect surfaceRect(QPoint(), window()->frameGeometry().size());
    QRect top(QPoint(), QSize(window()->frameGeometry().width(), margins().top()));

    QPainter p(device);
    p.setRenderHint(QPainter::Antialiasing);

    // Title bar
    int radius = waylandWindow()->isMaximized() ? 0 : dp(3);
    QPainterPath roundedRect;
    roundedRect.addRoundedRect(0, 0, window()->frameGeometry().width(), margins().top() * 1.5,
                               radius, radius);

    p.fillPath(roundedRect.simplified(), m_backgroundColor);

    // Window icon
    QIcon icon = waylandWindow()->windowIcon();
    if (!icon.isNull()) {
        QPixmap pixmap = icon.pixmap(QSize(128, 128));
        QPixmap scaled = pixmap.scaled(22, 22, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

        QRectF iconRect(0, 0, 22, 22);
        p.drawPixmap(iconRect.adjusted(margins().left() + BUTTON_SPACING, 4,
                                       margins().left() + BUTTON_SPACING, 4),
                     scaled, iconRect);
    }

    // Window title
    QString windowTitleText = window()->title();
    if (!windowTitleText.isEmpty()) {
        if (m_windowTitle.text() != windowTitleText) {
            m_windowTitle.setText(windowTitleText);
            m_windowTitle.prepare();
        }

        QRect titleBar = top;
        titleBar.setLeft(margins().left() + BUTTON_SPACING +
                         (icon.isNull() ? 0 : 22 + BUTTON_SPACING));
        titleBar.setRight(minimizeButtonRect().left() - BUTTON_SPACING);

        p.save();
        p.setClipRect(titleBar);
        p.setPen(m_textColor);
        QSizeF size = m_windowTitle.size();
        int dx = (top.width() - size.width()) / 2;
        int dy = (top.height() - size.height()) / 2;
        QFont font = p.font();
        font.setBold(true);
        font.setFamily("Roboto");
        p.setFont(font);
        QPoint windowTitlePoint(top.topLeft().x() + dx, top.topLeft().y() + dy);
        p.drawStaticText(windowTitlePoint, m_windowTitle);
        p.restore();
    }

    p.save();
    p.setPen(m_iconColor);

    // Close button
    QBitmap closeIcon = buttonIcon("window-close");
    p.drawPixmap(closeButtonRect(), closeIcon, closeIcon.rect());

    // Maximize button
    QBitmap maximizeIcon =
            buttonIcon(waylandWindow()->isMaximized() ? "window-restore" : "window-maximize");
    p.drawPixmap(maximizeButtonRect(), maximizeIcon, maximizeIcon.rect());

    // Minimize button
    QBitmap minimizeIcon = buttonIcon("window-minimize");
    p.drawPixmap(minimizeButtonRect(), minimizeIcon, minimizeIcon.rect());

    p.restore();
}
Example #20
0
void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                 const QModelIndex &index) const
{
  QStyledItemDelegate::paint(painter,option,index);

  painter->save();

  QFont aliasFont = option.font;
  QFont subFont   = option.font;
  QFont errorFont = subFont;
  QFont progressFont = subFont;

  progressFont.setPointSize( subFont.pointSize()-1);
  //font.setPixelSize(font.weight()+);
  aliasFont.setBold(true);
  aliasFont.setPointSize( subFont.pointSize()+2 );

  QFontMetrics subFm( subFont );
  QFontMetrics aliasFm( aliasFont );
  QFontMetrics progressFm( progressFont );

  int aliasMargin = aliasFm.height()/2;
  int margin = subFm.height()/4;

  QIcon statusIcon      = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
  QString aliasText     = qvariant_cast<QString>(index.data(FolderAliasRole));
  QString pathText      = qvariant_cast<QString>(index.data(FolderPathRole));
  QString remotePath    = qvariant_cast<QString>(index.data(FolderSecondPathRole));
  QStringList errorTexts= qvariant_cast<QStringList>(index.data(FolderErrorMsg));

  int overallPercent    = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
  QString overallString = qvariant_cast<QString>(index.data(SyncProgressOverallString));
  QString itemString    = qvariant_cast<QString>(index.data(SyncProgressItemString));
  int warningCount      = qvariant_cast<int>(index.data(WarningCount));
  bool syncOngoing      = qvariant_cast<bool>(index.data(SyncRunning));
  // QString statusText = qvariant_cast<QString>(index.data(FolderStatus));
  bool syncEnabled = index.data(FolderSyncEnabled).toBool();
  // QString syncStatus = syncEnabled? tr( "Enabled" ) : tr( "Disabled" );

  QRect iconRect = option.rect;
  QRect aliasRect = option.rect;

  iconRect.setLeft( aliasMargin );
  iconRect.setTop( iconRect.top() + aliasMargin ); // (iconRect.height()-iconsize.height())/2);

  // alias box
  aliasRect.setTop(aliasRect.top() + aliasMargin );
  aliasRect.setBottom(aliasRect.top() + aliasFm.height());
  aliasRect.setRight(aliasRect.right() - aliasMargin );

  // remote directory box
  QRect remotePathRect = aliasRect;
  remotePathRect.setTop(aliasRect.bottom() + margin );
  remotePathRect.setBottom(remotePathRect.top() + subFm.height());

  // local directory box
  QRect localPathRect = remotePathRect;
  localPathRect.setTop( remotePathRect.bottom() + margin );
  localPathRect.setBottom( localPathRect.top() + subFm.height());

  iconRect.setBottom(localPathRect.bottom());
  iconRect.setWidth(iconRect.height());

  int nextToIcon = iconRect.right()+aliasMargin;
  aliasRect.setLeft(nextToIcon);
  localPathRect.setLeft(nextToIcon);
  remotePathRect.setLeft(nextToIcon);

  int iconSize = iconRect.width();

  QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled );
  painter->drawPixmap(QPoint(iconRect.left(), iconRect.top()), pm);

  // only show the warning icon if the sync is running. Otherwise its
  // encoded in the status icon.
  if( warningCount > 0 && syncOngoing) {
      QRect warnRect;
      warnRect.setLeft(iconRect.left());
      warnRect.setTop(iconRect.bottom()-17);
      warnRect.setWidth(16);
      warnRect.setHeight(16);

      QIcon warnIcon(":/mirall/resources/warning-16");
      QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled );
      painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm );
  }

  if ((option.state & QStyle::State_Selected)
          && (option.state & QStyle::State_Active)
          // Hack: Windows Vista's light blue is not contrasting enough for white
          && !qApp->style()->inherits("QWindowsVistaStyle")) {
      painter->setPen(option.palette.color(QPalette::HighlightedText));
  } else {
      painter->setPen(option.palette.color(QPalette::Text));
  }
  QString elidedAlias = aliasFm.elidedText(aliasText, Qt::ElideRight, aliasRect.width());
  painter->setFont(aliasFont);
  painter->drawText(aliasRect, elidedAlias);

  painter->setFont(subFont);
  QString elidedRemotePathText;

  if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
      elidedRemotePathText = subFm.elidedText(tr("Syncing all files in your account with"),
                                              Qt::ElideRight, remotePathRect.width());
  } else {
      elidedRemotePathText = subFm.elidedText(tr("Remote path: %1").arg(remotePath),
                                              Qt::ElideMiddle, remotePathRect.width());
  }
  painter->drawText(remotePathRect, elidedRemotePathText);

  QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width());
  painter->drawText(localPathRect, elidedPathText);

  // paint an error overlay if there is an error string

  int h = iconRect.bottom();
  if( !errorTexts.isEmpty() ) {
      h += aliasMargin;
      QRect errorRect = localPathRect;
      errorRect.setLeft( iconRect.left());
      errorRect.setTop( h );
      errorRect.setHeight(errorTexts.count() * subFm.height()+aliasMargin);
      errorRect.setRight( option.rect.right()-aliasMargin );

      painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
      painter->setPen( QColor(0xaa, 0xaa, 0xaa));
      painter->drawRoundedRect( errorRect, 4, 4 );

      painter->setPen( Qt::white );
      painter->setFont(errorFont);
      QRect errorTextRect = errorRect;
      errorTextRect.setLeft( errorTextRect.left()+aliasMargin );
      errorTextRect.setTop( errorTextRect.top()+aliasMargin/2 );

      int x = errorTextRect.left();
      int y = errorTextRect.top()+aliasMargin/2 + subFm.height()/2;

      foreach( QString eText, errorTexts ) {
          painter->drawText(x, y, subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width()-2*aliasMargin));
          y += subFm.height();
      }
Example #21
0
void NMainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons() & Qt::LeftButton) && !isMaximized()) {
        if (m_dragActive) {
            move(event->globalPos() - m_dragPoint);
            event->accept();
        } else if (m_resizeActive) {
            QRect g = geometry();
            QRect origR = geometry();
            QPoint pos = event->globalPos() - m_resizePoint;
            switch (m_resizeSection) {
                case Qt::TopLeftSection:
                    g.setTopLeft(pos + m_resizeRect.topLeft());
                    break;
                case Qt::TopRightSection:
                    g.setTopRight(pos + m_resizeRect.topRight());
                    break;
                case Qt::BottomRightSection:
                    g.setBottomRight(pos + m_resizeRect.bottomRight());
                    break;
                case Qt::BottomLeftSection:
                    g.setBottomLeft(pos + m_resizeRect.bottomLeft());
                    break;
                case Qt::TopSection:
                    g.setTop(pos.y() + m_resizeRect.top());
                    break;
                case Qt::RightSection:
                    g.setRight(pos.x() + m_resizeRect.right());
                    break;
                case Qt::BottomSection:
                    g.setBottom(pos.y() + m_resizeRect.bottom());
                    break;
                case Qt::LeftSection:
                    g.setLeft(pos.x() + m_resizeRect.left());
                    break;
                default:
                    break;
            }
            QSize min = QLayout::closestAcceptableSize(this, g.size());
            QRect desk = QApplication::desktop()->availableGeometry(this);
            if (min.width() > g.width() || min.height() > g.height() ||
                desk.left() > g.left() || desk.right() < g.right() ||
                desk.top() > g.top() || desk.bottom() < g.bottom())
            {
                switch (m_resizeSection) {
                    case Qt::TopLeftSection:
                    case Qt::TopSection:
                    case Qt::LeftSection:
                        if (min.width() > g.width())
                            g.setLeft(origR.left());
                        else if (desk.left() > g.left())
                            g.setLeft(desk.left());
                        if (min.height() > g.height())
                            g.setTop(origR.top());
                        else if (desk.top() > g.top())
                            g.setTop(desk.top());
                        break;
                    case Qt::TopRightSection:
                        if (min.width() > g.width())
                            g.setRight(origR.right());
                        else if (desk.right() < g.right())
                            g.setRight(desk.right());
                        if (min.height() > g.height())
                            g.setTop(origR.top());
                        else if (desk.top() > g.top())
                            g.setTop(desk.top());
                        break;
                    case Qt::BottomRightSection:
                    case Qt::BottomSection:
                    case Qt::RightSection:
                        if (min.width() > g.width())
                            g.setRight(origR.right());
                        else if (desk.right() < g.right())
                            g.setRight(desk.right());
                        if (min.height() > g.height())
                            g.setBottom(origR.bottom());
                        else if (desk.bottom() < g.bottom())
                            g.setBottom(desk.bottom());
                        break;
                    case Qt::BottomLeftSection:
                        if (min.width() > g.width())
                            g.setLeft(origR.left());
                        else if (desk.left() > g.left())
                            g.setLeft(desk.left());
                        if (min.height() > g.height())
                            g.setBottom(origR.bottom());
                        else if (desk.bottom() < g.bottom())
                            g.setBottom(desk.bottom());
                        break;
                    default:
                        break;
                }
            }
            setGeometry(g);
        }
    }
}
Example #22
0
STDMETHODIMP UIFrameBufferQuartz2D::SetVisibleRegion(BYTE *aRectangles, ULONG aCount)
{
    PRTRECT rects = (PRTRECT)aRectangles;

    if (!rects)
        return E_POINTER;

    /** @todo r=bird: Is this thread safe? If I remember the code flow correctly, the
     * GUI thread could be happily jogging along paintEvent now on another cpu core.
     * This function is called on the EMT (emulation thread). Which means, blocking
     * execution waiting for a lock is out of the question. A quick solution using
     * ASMAtomic(Cmp)XchgPtr and a struct { cAllocated; cRects; aRects[1]; }
     * *mRegion, *mUnusedRegion; should suffice (and permit you to reuse allocations). */
    RegionRects *rgnRcts = ASMAtomicXchgPtrT(&mRegionUnused, NULL, RegionRects *);
    if (rgnRcts && rgnRcts->allocated < aCount)
    {
        RTMemFree (rgnRcts);
        rgnRcts = NULL;
    }
    if (!rgnRcts)
    {
        ULONG allocated = RT_ALIGN_32(aCount + 1, 32);
        allocated = RT_MAX (128, allocated);
        rgnRcts = (RegionRects *)RTMemAlloc(RT_OFFSETOF(RegionRects, rcts[allocated]));
        if (!rgnRcts)
            return E_OUTOFMEMORY;
        rgnRcts->allocated = allocated;
    }
    rgnRcts->used = 0;

    QRegion reg;
//    printf ("Region rects follow...\n");
    QRect vmScreenRect (0, 0, width(), height());
    for (ULONG ind = 0; ind < aCount; ++ ind)
    {
        QRect rect;
        rect.setLeft(rects->xLeft);
        rect.setTop(rects->yTop);
        /* QRect are inclusive */
        rect.setRight(rects->xRight - 1);
        rect.setBottom(rects->yBottom - 1);

        /* The rect should intersect with the vm screen. */
        rect = vmScreenRect.intersect(rect);
        ++ rects;
        /* Make sure only valid rects are distributed */
        /* todo: Test if the other framebuffer implementation have the same
         * problem with invalid rects (In Linux/Windows) */
        if (rect.isValid() &&
           rect.width() > 0 && rect.height() > 0)
            reg += rect;
        else
            continue;

        CGRect *cgRct = &rgnRcts->rcts[rgnRcts->used];
        cgRct->origin.x = rect.x();
        cgRct->origin.y = height() - rect.y() - rect.height();
        cgRct->size.width = rect.width();
        cgRct->size.height = rect.height();
//        printf ("Region rect[%d - %d]: %d %d %d %d\n", rgnRcts->used, aCount, rect.x(), rect.y(), rect.height(), rect.width());
        rgnRcts->used++;
    }
//    printf ("..................................\n");

    RegionRects *pOld = ASMAtomicXchgPtrT(&mRegion, rgnRcts, RegionRects *);
    if (    pOld
        &&  !ASMAtomicCmpXchgPtr(&mRegionUnused, pOld, NULL))
        RTMemFree(pOld);

    QApplication::postEvent(m_pMachineView, new UISetRegionEvent (reg));

    return S_OK;
}
Example #23
0
KviMainWindow::KviMainWindow(QWidget * pParent)
    : KviTalMainWindow(pParent, "kvirc_frame")
{
	g_pMainWindow = this;
	setAttribute(Qt::WA_DeleteOnClose);
	setAutoFillBackground(false);
	setAttribute(Qt::WA_TranslucentBackground);
	//disable this flag that gets enabled by qt when using Qt::WA_TranslucentBackground
	setAttribute(Qt::WA_NoSystemBackground, false);
#if !(defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) || defined(COMPILE_KDE_SUPPORT))
	// Under windows, the icon is builtin; under kde, KApplication sets it for us
	// We try to avois this as much as possible, since it forces the use of the low-res 16x16 icon
	setWindowIcon(*(g_pIconManager->getSmallIcon(KviIconManager::KVIrc)));
#endif

	m_pWinList = new KviPointerList<KviWindow>;
	setWindowTitle(KVI_DEFAULT_FRAME_CAPTION);
	m_pWinList->setAutoDelete(false);

	m_pModuleExtensionToolBarList = new KviPointerList<KviMexToolBar>;
	m_pModuleExtensionToolBarList->setAutoDelete(false);

	m_pActiveContext = nullptr;

	m_pTrayIcon = nullptr;

	m_pSplitter = new QSplitter(Qt::Horizontal, this);
	m_pSplitter->setObjectName("main_frame_splitter");
	m_pSplitter->setChildrenCollapsible(false);

	setCentralWidget(m_pSplitter);

	setIconSize(KVI_OPTION_UINT(KviOption_uintToolBarIconSize));
	setButtonStyle(KVI_OPTION_UINT(KviOption_uintToolBarButtonStyle));

	m_pWindowStack = new KviWindowStack(m_pSplitter, "mdi_manager");

	// This theoretically had to exists before KviWindowStack (that uses enterSdiMode)
	m_pAccellerators = new KviPointerList<QShortcut>;
	m_pMenuBar = new KviMenuBar(this, "main_menu_bar");
	setMenuWidget(m_pMenuBar);
#ifndef COMPILE_ON_MAC
	m_pMenuBar->setVisible(KVI_OPTION_BOOL(KviOption_boolMenuBarVisible));
#endif

	if(KVI_OPTION_BOOL(KviOption_boolStatusBarVisible))
	{
		m_pStatusBar = new KviStatusBar(this);
		setStatusBar(m_pStatusBar);
		// torque: moved out of status bar constructor
		// because module init functions executed in load()
		// couldn't access the status bar via g_pMainWindow->mainStatusBar()
		// (assignment of m_pStatusBar happened after load() and
		// the init function)
		m_pStatusBar->load();
	}
	else
	{
		m_pStatusBar = nullptr;
	}

	m_pWindowList = nullptr;

	createWindowList();

	if((KVI_OPTION_RECT(KviOption_rectFrameGeometry).width() < 100) || (KVI_OPTION_RECT(KviOption_rectFrameGeometry).height() < 100) || (KVI_OPTION_RECT(KviOption_rectFrameGeometry).x() > g_pApp->desktop()->width()) || (KVI_OPTION_RECT(KviOption_rectFrameGeometry).y() > g_pApp->desktop()->height()))
	{
		// Try to find some reasonable defaults
		// prefer primary screen for first startup
		int primary_screen = g_pApp->desktop()->primaryScreen();
		QRect r = g_pApp->desktop()->screenGeometry(primary_screen);
		r.setLeft(r.left() + 10);
		r.setRight(r.right() - 100);
		r.setTop(r.top() + 10);
		r.setBottom(r.bottom() - 200);
		KVI_OPTION_RECT(KviOption_rectFrameGeometry) = r;
	}

	resize(KVI_OPTION_RECT(KviOption_rectFrameGeometry).width(),
	    KVI_OPTION_RECT(KviOption_rectFrameGeometry).height());
	move(KVI_OPTION_RECT(KviOption_rectFrameGeometry).x(),
	    KVI_OPTION_RECT(KviOption_rectFrameGeometry).y());

	if(KVI_OPTION_BOOL(KviOption_boolFrameIsMaximized))
		showMaximized();

	applyOptions();

	installAccelerators();
}
void KdeConnectDevicesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    painter->setFont(option.font);

    QRect iconRect;
    if (((QListView*) option.widget)->viewMode() == QListView::IconMode) {
        iconRect.setLeft(option.rect.left() + 38 * getDPIScaling());
        iconRect.setTop(option.rect.top() + 6 * getDPIScaling());
        iconRect.setHeight(32 * getDPIScaling());
        iconRect.setWidth(32 * getDPIScaling());

        QRect textRect;
        textRect.setLeft(option.rect.left() + 6 * getDPIScaling());
        textRect.setTop(iconRect.bottom() + 6 * getDPIScaling());
        textRect.setBottom(option.rect.bottom());
        textRect.setRight(option.rect.right());

        if (option.state & QStyle::State_Selected) {
            painter->setPen(Qt::transparent);
            painter->setBrush(option.palette.color(QPalette::Highlight));
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::HighlightedText));
            painter->drawText(textRect, index.data().toString());
        } else if (option.state & QStyle::State_MouseOver) {
            QColor col = option.palette.color(QPalette::Highlight);
            col.setAlpha(127);
            painter->setBrush(col);
            painter->setPen(Qt::transparent);
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
        } else {
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
        }
    } else {
        iconRect.setLeft(option.rect.left() + 12 * getDPIScaling());
        iconRect.setTop(option.rect.top() + 6 * getDPIScaling());
        iconRect.setBottom(iconRect.top() + 32 * getDPIScaling());
        iconRect.setRight(iconRect.left() + 32 * getDPIScaling());

        QRect textRect;
        textRect.setLeft(iconRect.right() + 6 * getDPIScaling());
        textRect.setTop(option.rect.top() + 6 * getDPIScaling());
        textRect.setBottom(option.rect.top() + option.fontMetrics.height() + 6 * getDPIScaling());
        textRect.setRight(option.rect.right());

        QRect descRect;
        descRect.setLeft(iconRect.right() + 6 * getDPIScaling());
        descRect.setTop(option.rect.top() + option.fontMetrics.height() + 8 * getDPIScaling());
        descRect.setBottom(option.rect.top() + option.fontMetrics.height() * 2 + 6 * getDPIScaling());
        descRect.setRight(option.rect.right());

        if (option.state & QStyle::State_Selected) {
            painter->setPen(Qt::transparent);
            painter->setBrush(option.palette.color(QPalette::Highlight));
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::HighlightedText));
            painter->drawText(textRect, index.data().toString());
            painter->drawText(descRect, index.data(Qt::UserRole).toString());
        } else if (option.state & QStyle::State_MouseOver) {
            QColor col = option.palette.color(QPalette::Highlight);
            col.setAlpha(127);
            painter->setBrush(col);
            painter->setPen(Qt::transparent);
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
            painter->setPen(option.palette.color(QPalette::Disabled, QPalette::WindowText));
            painter->drawText(descRect, index.data(Qt::UserRole).toString());
        } else {
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
            painter->setPen(option.palette.color(QPalette::Disabled, QPalette::WindowText));
            painter->drawText(descRect, index.data(Qt::UserRole).toString());
        }
    }
    painter->drawPixmap(iconRect, index.data(Qt::DecorationRole).value<QIcon>().pixmap(iconRect.size()));

    QDBusInterface device("org.kde.kdeconnect", "/modules/kdeconnect/devices/" + index.data(Qt::UserRole + 1).toString(), "org.kde.kdeconnect.device");
    bool reachable = device.property("isReachable").toBool();
    bool trusted = device.property("isTrusted").toBool();

    if (reachable && trusted) {
        painter->setBrush(QColor(0, 100, 0));
        painter->setPen(Qt::transparent);
        painter->drawRect(option.rect.left(), option.rect.top(), 6 * getDPIScaling(), option.rect.height());
    }
}
Example #25
0
/*!
  \brief Draw the contents inside the frame
 
  QColorGroup::Background is the background color outside of the frame.
  QColorGroup::Base is the background color inside the frame.
  QColorGroup::Foreground is the background color inside the scale.

  \param painter Painter
  \sa QwtDial::boundingRect, QwtDial::contentsRect,
    QwtDial::scaleContentsRect, QWidget::setPalette
*/
void QwtDial::drawContents(QPainter *painter) const
{
    if ( backgroundMode() == NoBackground || 
        colorGroup().brush(QColorGroup::Base) != 
            colorGroup().brush(QColorGroup::Background) )
    {
        // Don´t use QPainter::drawEllipse. There are some pixels
        // different compared to the region in the mask, leaving
        // them in background color.

        painter->save();
        painter->setPen(Qt::NoPen);
        painter->setBrush(colorGroup().brush(QColorGroup::Base));

        // Even if we want to fill the contentsRect only, we fill the
        // complete boundingRect. The frame will be painted later
        // above, but we want to have the base color below it
        // because round objects doesn´t cover all pixels.

        QRect br = boundingRect();
#if QT_VERSION < 300
#ifdef _WS_WIN32_
        // Qt-230-NC draws ellipses not as nicely as Qt-2.3.x on X Windows
        br.setTop(br.top()-1);
        br.setLeft(br.left()-1);
        br.setBottom(br.bottom()+1);
        br.setRight(br.right()+1);
#endif
#endif
        painter->setClipRegion(QRegion(painter->xForm(br), QRegion::Ellipse));
        painter->drawRect(br);
        painter->restore();
    }


    const QRect insideScaleRect = scaleContentsRect();
    if ( colorGroup().brush(QColorGroup::Foreground) !=
        colorGroup().brush(QColorGroup::Base) )
    {
        painter->save();
        painter->setPen(Qt::NoPen);
        painter->setBrush(colorGroup().brush(QColorGroup::Foreground));

        painter->setClipRegion(
            QRegion(painter->xForm(insideScaleRect), QRegion::Ellipse));
        painter->drawRect(insideScaleRect);
        painter->restore();
    }

    const QPoint center = insideScaleRect.center();
    const int radius = insideScaleRect.width() / 2;

    painter->save();
    drawScaleContents(painter, center, radius);
    painter->restore();

    double direction = d_origin;

    if (isValid())
    {
        direction = d_origin + d_minScaleArc;
        if ( maxValue() > minValue() && d_maxScaleArc > d_minScaleArc )
        {
            const double ratio = 
                (value() - minValue()) / (maxValue() - minValue());
            direction += ratio * (d_maxScaleArc - d_minScaleArc);
        }

        if ( direction >= 360.0 )
            direction -= 360.0;
    }

    double origin = d_origin;
    if ( mode() == RotateScale )
    {
        origin -= direction - d_origin;
        direction = d_origin;
    }

    painter->save();
    drawScale(painter, center, radius, origin, d_minScaleArc, d_maxScaleArc);
    painter->restore();

    if ( isValid() )
    {
        QPalette::ColorGroup cg;
        if ( isEnabled() )
            cg = hasFocus() ? QPalette::Active : QPalette::Inactive;
        else
            cg = QPalette::Disabled;

        painter->save();
        drawNeedle(painter, center, radius, direction, cg);
        painter->restore();
    }
}
Example #26
0
void PluginItemDelegate::paint( QPainter *painter,
                                const QStyleOptionViewItem& option,
                                const QModelIndex& index ) const
{
    Q_ASSERT( index.isValid() );
    QRect rect = option.rect;
    QStyle *style = QApplication::style();

    painter->save();

    // Drawing the background
    QStyleOption background = option;
    style->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter );

    painter->translate( rect.topLeft() );

    // rect is now represented in item coordinates
    rect.moveTopLeft( QPoint( 0, 0 ) );
    // The point at the top left of the available drawing area.
    QPoint topLeft( 0, 0 );
    // The point at the top right of the available drawing area.
    QPoint topRight( rect.topRight() );

    QRect nameRect = rect;
    
    // Painting the checkbox
    QStyleOptionButton checkBox = checkboxOption( option, index, topLeft.x(), Qt::AlignLeft );
    painter->save();
    style->drawControl( QStyle::CE_CheckBox, &checkBox, painter );
    painter->restore();

    nameRect.setLeft( checkBox.rect.right() + 1 );
    
    // Painting the About Button
    if ( index.data( RenderPlugin::AboutDialogAvailable ).toBool() ) {
        QStyleOptionButton button = buttonOption( option, index, PluginItemDelegate::About,
                                                  topRight.x(), Qt::AlignRight );
        style->drawControl( QStyle::CE_PushButton, &button, painter );
        topRight -= QPoint( button.rect.width(), 0 );
    }

    // Painting the Configure Button
    if ( index.data( RenderPlugin::ConfigurationDialogAvailable ).toBool() ) {
        QStyleOptionButton button = buttonOption( option, index, PluginItemDelegate::Configure,
                                                  topRight.x(), Qt::AlignRight );
        style->drawControl( QStyle::CE_PushButton, &button, painter );
        topRight -= QPoint( button.rect.width(), 0 );
        
        nameRect.setRight( button.rect.left() -1 );
    }

    // Painting the Name string
    QString name = index.data( Qt::DisplayRole ).toString();
    
    style->drawItemText( painter,
                         nameRect,
                         Qt::AlignLeft | Qt::AlignVCenter,
                         option.palette,
                         true,
                         name );

    painter->restore();
}
void CWizUserInfoWidgetBase::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    int nAvatarWidth = 36;
    int nArrawWidth = 10;
    int nMargin = 4;

    QStyleOptionToolButton opt;
    initStyleOption(&opt);

    QPainter p(this);
    p.setClipRect(opt.rect);

    // draw user avatar
    QRect rectIcon = opt.rect;
    rectIcon.setLeft(rectIcon.left());
    rectIcon.setRight(rectIcon.left() + nAvatarWidth);

    QPixmap pixmap = getAvatar();
    if (!pixmap.isNull())
    {
        p.drawPixmap(rectIcon, pixmap);
    }
    //if (!opt.icon.isNull()) {
    //    opt.icon.paint(&p, rectIcon);
    //}

    // draw vip indicator
    QRect rectVip = rectIcon;
    rectVip.setLeft(rectVip.right() + nMargin);
    rectVip.setRight(rectVip.left() + fontMetrics().width(opt.text));
    //rectVip.setBottom(rectVip.top() + rectVip.height()/2);
    //if (!m_iconVipIndicator.isNull()) {
    //    m_iconVipIndicator.paint(&p, rectVip, Qt::AlignLeft|Qt::AlignTop);
    //}

    // draw display name
    QRect rectText = rectVip;
    //rectText.setBottom(rectText.bottom() + rectVip.height());
    //rectText.setTop(rectText.bottom() - rectVip.height());
    if (!opt.text.isEmpty()) {
        if (opt.state & QStyle::State_MouseOver) {
            QFont font = p.font();
            font.setUnderline(true);
            p.setFont(font);
        }

        p.setPen("#787878"); // FIXME
        p.drawText(rectText, Qt::AlignLeft|Qt::AlignVCenter, opt.text);
    }

    // draw arraw
    QRect rectArrow = rectText;
    rectArrow.setLeft(rectArrow.right() + nMargin);
    rectArrow.setRight(rectArrow.left() + nArrawWidth);
    QIcon arrow = getArrow();
    if (!arrow.isNull()) {
        arrow.paint(&p, rectArrow, Qt::AlignVCenter, QIcon::Normal);
    }
}
Example #28
0
void View::setXPos(int x)
      {
      int delta  = xpos - x;         // -  -> shift left
      xpos  = x;
      
      #ifdef VIEW_USE_DOUBLE_BUFFERING
      if (pm.isNull())
            return;
      if (!pmValid) {
            //printf("View::setXPos !pmValid x:%d width:%d delta:%d\n", x, width(), delta);
            redraw();
            return;
            }
            
      int w = width();
      int h = height();

      QRect r;
      if (delta >= w || delta <= -w)
            r = QRect(0, 0, w, h);
      else if (delta < 0) {   // shift left
            //bitBlt(&pm,  0, 0, &pm,  -delta, 0, w + delta, h, CopyROP, true);
            QPainter p(&pm);
            p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing, false);
            //printf("View::setXPos x:%d w:%d delta:%d r.x:%d r.w:%d\n", 
            //  x, w, delta, r.x(), r.width());                    
            p.drawPixmap(0, 0, pm, -delta, 0, w + delta, h);
            r = QRect(w + delta, 0, -delta, h);
            }
      else {                  // shift right
            //bitBlt(&pm,  delta, 0, &pm,     0, 0, w-delta, h, CopyROP, true);
            QPainter p(&pm);
            p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing, false);
            //printf("View::setXPos x:%d w:%d delta:%d r.x:%d r.w:%d\n", 
            //  x, w, delta, r.x(), r.width());                    
            p.drawPixmap(delta, 0, pm,     0, 0, w-delta, h);
            r = QRect(0, 0, delta, h);
            }
      QRect olr = overlayRect();
      QRect olr1(olr);
      olr1.translate(delta, 0);

      r |= olr;
      r |= olr1;
      
      //printf("View::setXPos x:%d w:%d delta:%d r.x:%d r.w:%d\n", x, w, delta, r.x(), r.width());
      //printf("View::setXPos paint delta:%d r.x:%d r.y:%d r.w:%d r.h:%d\n", delta, r.x(), r.y(), r.width(), r.height());  
      
      paint(r);
      update();
      
      #else
      scroll(delta, 0);
      QRect olr = overlayRect();
      // Is there an overlay?
      if(!olr.isNull())
      {
        // Are we shifting right (moving left)?
        if(delta >= 0)
        {
          // Translate not good - need to set x to delta.
          //olr.translate(delta, 0);
          olr.setX(delta);
          olr.setWidth(olr.x() + olr.width() + delta);
        }
        else
        // We are shifting left (moving right).
        {
          // Translate not good - need to limit x to 0.
          //olr.translate(delta, 0);
          olr.setX(olr.x() + delta);
        }
        
        if(olr.x() < 0)
          olr.setX(0);
        if(olr.right() > width())
          olr.setRight(width());
        
        if(olr.y() < 0)
          olr.setY(0);
        if(olr.bottom() > height())
          olr.setBottom(height());
        
        //printf("scroll X update: x:%d y:%d w:%d h:%d\n", olr.x(), olr.y(), olr.width(), olr.height()); 
        update(olr);
      }  
      #endif
      }
void BuildFontDialog::displayPage()
{
  originalPage = doc->page(currentPage)->renderToImage(150, 150);
  PIX* pix  = NCSAWordSpottingUtil::qImage2PIX(originalPage);
  
  tesseract::TessBaseAPI tess;
    tess.Init(NULL, "eng");
    
    tess.SetImage(pix);

    tess.Recognize(NULL);
    tesseract::ResultIterator* ri = tess.GetIterator();
    tesseract::ChoiceIterator* ci;
    
    boxedPage = originalPage.copy();
    QPainter p;
    p.begin(&boxedPage);
    p.setPen(Qt::red);
    letterRects.clear();
    
    QRect lastLetterBoxTight(0,0,0,0);
    QRect lastWordBox(0,0,0,0);

    if(ri != NULL)
    {
      do
      {
	int left, top, right, bottom;
	ri->BoundingBox(tesseract::RIL_SYMBOL, &left, &top, &right, &bottom);
	int x1, y1, x2, y2;
	ri->Baseline(tesseract::RIL_SYMBOL, &x1, &y1, &x2, &y2);
	int baseline = y1 + ((left+right)/2-x1)*(y2-y1)/(x2-x1);
	baseline = baseline - top;
	QRect letterBoxTight = QRect(left, top, right-left, bottom-top);
	QRect letterBox = letterBoxTight;
	QRect wordBox = letterBoxTight;
	//tightLetterBox2Box[letterBoxTight] = letterBox;
	
	wordBox.setLeft(x1);
	wordBox.setRight(x2);
	letterRects.push_back(letterBoxTight);
	baselines.push_back(baseline);
	p.drawRect(letterBoxTight);
	
	/*
	if (lastLetterBoxTight.x() <= wordBox.x())
	{
	  QRect lastLetterBox = tightLetterBox2Box[lastLetterBoxTight];
	  int X1 = lastLetterBoxTight.x()+lastLetterBoxTight.width();
	  int X2 = letterBoxTight.x();
	  tightLetterBox2Box[lastLetterBoxTight] = QRect(lastLetterBox.x(),lastLetterBox.top(), (X1+X2)/2 - lastLetterBox.x(), lastLetterBox.height());
	  tightLetterBox2Box[letterBoxTight] = QRect((X1+X2)/2,letterBox.top(), letterBox.width(), letterBox.height());

	}*/
	
	lastLetterBoxTight = letterBoxTight;
	lastWordBox = wordBox;

      }
      while(ri->Next(tesseract::RIL_SYMBOL));
    }
    p.end();
      
  
  imageLabel->setPixmap(QPixmap::fromImage(originalPage));
  imageLabel->adjustSize();
  QString pageText;
  pageText.append(QString::number(currentPage+1));
  pageText.append("/");
  pageText.append(QString::number(doc->numPages()));
  pageIndicator->setText(pageText);
  
  isBoxedDisplay.checkedButton()->click();


}
Example #30
0
void CodeView::paintEvent ( QPaintEvent * event )
{
    int rowHeight = getRowHeight();
    QColor darkRed(100,0,0);
    QPainter painter(this);

    // Draw background
    painter.fillRect(event->rect(), Qt::black);



    // Border
    QRect rect = event->rect();
    rect.setRight(BORDER_WIDTH);
    QColor borderColor;
    borderColor = QColor(60,60,60);
    painter.fillRect(rect, borderColor);


    // Show breakpoints
    for(int j = 0;j < m_breakpointList.size();j++)
    {
        int lineNo = m_breakpointList[j];
        int rowIdx = lineNo-1;
        int y = rowHeight*rowIdx;
        QRect rect2(5,y,BORDER_WIDTH-10,rowHeight);
        painter.fillRect(rect2, Qt::blue);
    }

    
    // Draw content
    painter.setFont(m_font);
    for(size_t rowIdx = 0;rowIdx < m_highlighter.getRowCount();rowIdx++)
    {
        //int x = BORDER_WIDTH+10;
        int y = rowHeight*rowIdx;
        QString nrText;


    if((int)rowIdx == m_cursorY-1)
    {
        QRect rect2(BORDER_WIDTH,y,event->rect().width()-1,rowHeight);
        painter.fillRect(rect2, darkRed);
    }

        int fontY = y+(rowHeight-(m_fontInfo->ascent()+m_fontInfo->descent()))/2+m_fontInfo->ascent();
        painter.setPen(Qt::white);
        nrText = QString("%1").arg(rowIdx+1);
        painter.drawText(4, fontY, nrText);

        QVector<TextField*> cols = m_highlighter.getRow(rowIdx);
        
        int x = BORDER_WIDTH+10;
        for(int j = 0;j < cols.size();j++)
        {

            TextField *field = cols[j];            

            painter.setPen(field->m_color);
            painter.drawText(x, fontY, field->m_text);

            x += m_fontInfo->width(field->m_text);

        }
    }

}