Example #1
0
bool DeviceSkinParameters::read(QTextStream &ts, ReadMode rm, QString *errorMessage)
{
    QStringList closedAreas;
    QStringList toggleAreas;
    QStringList toggleActiveAreas;
    int nareas = 0;
    screenDepth = 0;
    QString mark;
    ts >> mark;
    hasMouseHover = true; // historical default
    if ( mark == QLatin1String("[SkinFile]") ) {
        const QString UpKey = QLatin1String("Up");
        const QString DownKey = QLatin1String("Down");
        const QString ClosedKey = QLatin1String("Closed");
        const QString ClosedAreasKey = QLatin1String("ClosedAreas");
        const QString ScreenKey = QLatin1String("Screen");
        const QString ScreenDepthKey = QLatin1String("ScreenDepth");
        const QString BackScreenKey = QLatin1String("BackScreen");
        const QString ClosedScreenKey = QLatin1String("ClosedScreen");
        const QString CursorKey = QLatin1String("Cursor");
        const QString AreasKey = QLatin1String("Areas");
        const QString ToggleAreasKey = QLatin1String("ToggleAreas");
        const QString ToggleActiveAreasKey = QLatin1String("ToggleActiveAreas");
        const QString HasMouseHoverKey = QLatin1String("HasMouseHover");
        // New
        while (!nareas) {
            QString line = ts.readLine();
            if ( line.isNull() )
                break;
            if ( line[0] != QLatin1Char('#') && !line.isEmpty() ) {
                int eq = line.indexOf(QLatin1Char('='));
                if ( eq >= 0 ) {
                    const QString key = line.left(eq);
                    eq++;
                    while (eq<line.length()-1 && line[eq].isSpace())
                        eq++;
                    const QString value = line.mid(eq);
                    if ( key == UpKey ) {
                        skinImageUpFileName = value;
                    } else if ( key == DownKey ) {
                        skinImageDownFileName = value;
                    } else if ( key ==  ClosedKey ) {
                        skinImageClosedFileName = value;
                    } else if ( key == ClosedAreasKey ) {
                        closedAreas = value.split(QLatin1Char(' '));
                    } else if ( key == ScreenKey ) {
                        parseRect( value, &screenRect);
                    } else if ( key == ScreenDepthKey ) {
                        screenDepth = value.toInt();
                    } else if ( key == BackScreenKey ) {
                        parseRect(value, &backScreenRect);
                    } else if ( key == ClosedScreenKey ) {
                        parseRect( value, &closedScreenRect );
                    } else if ( key == CursorKey ) {
                        QStringList l = value.split(QLatin1Char(' '));
                        skinCursorFileName = l[0];
                        cursorHot = QPoint(l[1].toInt(),l[2].toInt());
                    } else if ( key == AreasKey ) {
                        nareas = value.toInt();
                    } else if ( key == ToggleAreasKey ) {
                        toggleAreas = value.split(QLatin1Char(' '));
                    } else if ( key == ToggleActiveAreasKey ) {
                        toggleActiveAreas = value.split(QLatin1Char(' '));
                    } else if ( key == HasMouseHoverKey ) {
                        hasMouseHover = value == QLatin1String("true") || value == QLatin1String("1");
                    }
                } else {
                    *errorMessage =  DeviceSkin::tr("Syntax error: %1").arg(line);
                    return false;
                }
            }
        }
    } else {
        // Old
        skinImageUpFileName = mark;
        QString s;
        int x,y,w,h,na;
        ts >> s >> x >> y >> w >> h >> na;
        skinImageDownFileName = s;
        screenRect.setRect(x, y, w, h);
        nareas = na;
    }
    // Done for short mode
    if (rm ==  ReadSizeOnly)
        return true;
    //  verify skin files exist
    skinImageUpFileName.insert(0, prefix);
    if (!QFile(skinImageUpFileName).exists()) {
        *errorMessage =  DeviceSkin::tr("The skin \"up\" image file '%1' does not exist.").arg(skinImageUpFileName);
        return false;
    }
    if (!skinImageUp.load(skinImageUpFileName)) {
        *errorMessage = msgImageNotLoaded(skinImageUpFileName);
        return false;
    }

    skinImageDownFileName.insert(0, prefix);
    if (!QFile(skinImageDownFileName).exists()) {
        *errorMessage =  DeviceSkin::tr("The skin \"down\" image file '%1' does not exist.").arg(skinImageDownFileName);
        return false;
    }
    if (!skinImageDown.load(skinImageDownFileName)) {
        *errorMessage = msgImageNotLoaded(skinImageDownFileName);
        return false;
    }

    if (!skinImageClosedFileName.isEmpty()) {
        skinImageClosedFileName.insert(0, prefix);
        if (!QFile(skinImageClosedFileName).exists()) {
            *errorMessage =  DeviceSkin::tr("The skin \"closed\" image file '%1' does not exist.").arg(skinImageClosedFileName);
            return false;
        }
        if (!skinImageClosed.load(skinImageClosedFileName)) {
            *errorMessage = msgImageNotLoaded(skinImageClosedFileName);
            return false;
        }
    }

    if (!skinCursorFileName.isEmpty()) {
        skinCursorFileName.insert(0, prefix);
        if (!QFile(skinCursorFileName).exists()) {
            *errorMessage =  DeviceSkin::tr("The skin cursor image file '%1' does not exist.").arg(skinCursorFileName);
            return false;
        }
        if (!skinCursor.load(skinCursorFileName)) {
            *errorMessage = msgImageNotLoaded(skinCursorFileName);
            return false;
        }
    }

    // read areas
    if (!nareas)
        return true;
    buttonAreas.reserve(nareas);

    int i = 0;
    ts.readLine(); // eol
    joystick = -1;
    const QString Joystick = QLatin1String("Joystick");
    while (i < nareas && !ts.atEnd() ) {
        buttonAreas.push_back(DeviceSkinButtonArea());
        DeviceSkinButtonArea &area = buttonAreas.back();
        const QString line = ts.readLine();
        if ( !line.isEmpty() && line[0] != QLatin1Char('#') ) {
            const QStringList tok = line.split(QRegExp(QLatin1String("[ \t][ \t]*")));
            if ( tok.count()<6 ) {
                *errorMessage =  DeviceSkin::tr("Syntax error in area definition: %1").arg(line);
                return false;
            } else {
                area.name = tok[0];
                QString k = tok[1];
                if ( k.left(2).toLower() == QLatin1String("0x")) {
                    area.keyCode = k.mid(2).toInt(0,16);
                } else {
                    area.keyCode = k.toInt();
                }

                int p=0;
                for (int j=2; j < tok.count() - 1; ) {
                    const int x = tok[j++].toInt();
                    const int y = tok[j++].toInt();
                    area.area.putPoints(p++,1,x,y);
                }

                const QChar doubleQuote = QLatin1Char('"');
                if ( area.name[0] == doubleQuote && area.name.endsWith(doubleQuote)) {
                    area.name.truncate(area.name.size() - 1);
                    area.name.remove(0, 1);
                }
                if ( area.name.length() == 1 )
                    area.text = area.name;
                if ( area.name == Joystick)
                    joystick = i;
                area.activeWhenClosed = closedAreas.contains(area.name)
                    || area.keyCode == Qt::Key_Flip; // must be to work
		area.toggleArea = toggleAreas.contains(area.name);
		area.toggleActiveArea = toggleActiveAreas.contains(area.name);
		if ( area.toggleArea )
		    toggleAreaList += i;
                i++;
            }
        }
    }
    if (i != nareas) {
        qWarning() << DeviceSkin::tr("Mismatch in number of areas, expected %1, got %2.")
                      .arg(nareas).arg(i);
    }
    if (debugDeviceSkin)
	qDebug() << *this;
    return true;
}
void RToolMatrixItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    const QAbstractItemModel* model = index.model();
    Q_ASSERT(model);

    if (!model->parent(index).isValid()) {
//        bool hidden = model->data(index, Qt::UserRole+2).toBool();
//        qDebug() << "hidden: " << hidden;
//        if (hidden) {
//            return;
//        }

        // this is a top-level item.
        QStyleOptionButton buttonOption;

        buttonOption.state = option.state;
#ifdef Q_OS_MAC
        buttonOption.state |= QStyle::State_Raised;
#endif
        buttonOption.state &= ~QStyle::State_HasFocus;

        buttonOption.rect = option.rect;
        buttonOption.palette = option.palette;
        buttonOption.features = QStyleOptionButton::None;

        painter->save();
        QColor buttonColor(230, 230, 230);
        QBrush buttonBrush = option.palette.button();
        if (!buttonBrush.gradient() && buttonBrush.texture().isNull()) {
            buttonColor = buttonBrush.color();
        }
        QColor outlineColor = buttonColor.darker(150);
        QColor highlightColor = buttonColor.lighter(130);

        // Only draw topline if the previous item is expanded
        QModelIndex previousIndex = model->index(index.row() - 1, index.column());
        bool drawTopline = (index.row() > 0 && treeView->isExpanded(previousIndex));
        int highlightOffset = drawTopline ? 1 : 0;

        QLinearGradient gradient(option.rect.topLeft(), option.rect.bottomLeft());
        gradient.setColorAt(0, buttonColor.lighter(102));
        gradient.setColorAt(1, buttonColor.darker(106));

        painter->setPen(Qt::NoPen);
        painter->setBrush(gradient);
        painter->drawRect(option.rect);
        painter->setPen(highlightColor);
        painter->drawLine(option.rect.topLeft() + QPoint(0, highlightOffset),
                          option.rect.topRight() + QPoint(0, highlightOffset));
        painter->setPen(outlineColor);
        if (drawTopline) {
            painter->drawLine(option.rect.topLeft(), option.rect.topRight());
        }
        painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());
        painter->restore();

        QStyleOption branchOption;
        static const int i = 9;
        QRect r = option.rect;
        branchOption.rect = QRect(r.left() + i/2, r.top() + (r.height() - i)/2, i, i);
        branchOption.palette = option.palette;
        branchOption.state = QStyle::State_Children;

        if (treeView->isExpanded(index)) {
            branchOption.state |= QStyle::State_Open;
        }

        treeView->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, painter, treeView);

        // draw text
        QRect textrect = QRect(r.left() + i*2, r.top(), r.width() - ((5*i)/2), r.height());
        QString text = elidedText(option.fontMetrics, textrect.width(), Qt::ElideMiddle,
            model->data(index, Qt::DisplayRole).toString());
        treeView->style()->drawItemText(painter, textrect, Qt::AlignCenter,
            option.palette, treeView->isEnabled(), text);

    } else {
        QItemDelegate::paint(painter, option, index);
    }
}
void KviMircTextColorSelector::buttonClicked()
{
	QPoint p = m_pButton->mapToGlobal(QPoint(0,m_pButton->height()));
	m_pContextPopup->popup(p);
}
Example #4
0
void QLCDNumber::drawSegment( const QPoint &pos, char segmentNo, QPainter &p,
                              int segLen, bool erase )
{
    QPoint pt = pos;
    int width = segLen/5;

    const QColorGroup & g = colorGroup();
    QColor lightColor,darkColor,fgColor;
    if ( erase ){
        lightColor = backgroundColor();
        darkColor  = lightColor;
        fgColor    = lightColor;
    } else {
        lightColor = g.light();
        darkColor  = g.dark();
        fgColor    = g.foreground();
    }

#define LINETO(X,Y) addPoint( a, QPoint(pt.x() + (X),pt.y() + (Y)))
#define LIGHT
#define DARK

    if ( fill ) {
        QPointArray a(0);

        //The following is an exact copy of the switch below.
        //don't make any changes here
        switch ( segmentNo ) {
        case 0 :
            p.moveTo(pt);
            LIGHT;
            LINETO(segLen - 1,0);
            DARK;
            LINETO(segLen - width - 1,width);
            LINETO(width,width);
            LINETO(0,0);
            break;
        case 1 :
            pt += QPoint(0 , 1);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,width);
            DARK;
            LINETO(width,segLen - width/2 - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 2 :
            pt += QPoint(segLen - 1 , 1);
            p.moveTo(pt);
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width/2 - 2);
            LIGHT;
            LINETO(-width,width);
            LINETO(0,0);
            break;
        case 3 :
            pt += QPoint(0 , segLen);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,-width/2);
            LINETO(segLen - width - 1,-width/2);
            LINETO(segLen - 1,0);
            DARK;
            if (width & 1) {            // adjust for integer division error
                LINETO(segLen - width - 3,width/2 + 1);
                LINETO(width + 2,width/2 + 1);
            } else {
                LINETO(segLen - width - 1,width/2);
                LINETO(width,width/2);
            }
            LINETO(0,0);
            break;
        case 4 :
            pt += QPoint(0 , segLen + 1);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,width/2);
            DARK;
            LINETO(width,segLen - width - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 5 :
            pt += QPoint(segLen - 1 , segLen + 1);
            p.moveTo(pt);
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width - 2);
            LIGHT;
            LINETO(-width,width/2);
            LINETO(0,0);
            break;
        case 6 :
            pt += QPoint(0 , segLen*2);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,-width);
            LINETO(segLen - width - 1,-width);
            LINETO(segLen - 1,0);
            DARK;
            LINETO(0,0);
            break;
        case 7 :
            if ( smallPoint )   // if smallpoint place'.' between other digits
                pt += QPoint(segLen + width/2 , segLen*2);
            else
                pt += QPoint(segLen/2 , segLen*2);
            p.moveTo(pt);
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 8 :
            pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
            p.moveTo(pt);
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 9 :
            pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
            p.moveTo(pt);
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
#if defined(QT_CHECK_RANGE)
        default :
            qWarning( "QLCDNumber::drawSegment: (%s) Internal error."
                     "  Illegal segment id: %d\n",
                     name( "unnamed" ), segmentNo );
#endif
        }
        // End exact copy
        p.setPen( fgColor );
        p.setBrush( fgColor );
        p.drawPolygon( a );
        p.setBrush( NoBrush );

        pt = pos;
    }
#undef LINETO
#undef LIGHT
#undef DARK

#define LINETO(X,Y) p.lineTo(QPoint(pt.x() + (X),pt.y() + (Y)))
#define LIGHT p.setPen(lightColor)
#define DARK  p.setPen(darkColor)
    if ( shadow )
        switch ( segmentNo ) {
        case 0 :
            p.moveTo(pt);
            LIGHT;
            LINETO(segLen - 1,0);
            DARK;
            LINETO(segLen - width - 1,width);
            LINETO(width,width);
            LINETO(0,0);
            break;
        case 1 :
            pt += QPoint(0,1);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,width);
            DARK;
            LINETO(width,segLen - width/2 - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 2 :
            pt += QPoint(segLen - 1 , 1);
            p.moveTo(pt);
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width/2 - 2);
            LIGHT;
            LINETO(-width,width);
            LINETO(0,0);
            break;
        case 3 :
            pt += QPoint(0 , segLen);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,-width/2);
            LINETO(segLen - width - 1,-width/2);
            LINETO(segLen - 1,0);
            DARK;
            if (width & 1) {            // adjust for integer division error
                LINETO(segLen - width - 3,width/2 + 1);
                LINETO(width + 2,width/2 + 1);
            } else {
                LINETO(segLen - width - 1,width/2);
                LINETO(width,width/2);
            }
            LINETO(0,0);
            break;
        case 4 :
            pt += QPoint(0 , segLen + 1);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,width/2);
            DARK;
            LINETO(width,segLen - width - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 5 :
            pt += QPoint(segLen - 1 , segLen + 1);
            p.moveTo(pt);
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width - 2);
            LIGHT;
            LINETO(-width,width/2);
            LINETO(0,0);
            break;
        case 6 :
            pt += QPoint(0 , segLen*2);
            p.moveTo(pt);
            LIGHT;
            LINETO(width,-width);
            LINETO(segLen - width - 1,-width);
            LINETO(segLen - 1,0);
            DARK;
            LINETO(0,0);
            break;
        case 7 :
            if ( smallPoint )   // if smallpoint place'.' between other digits
                pt += QPoint(segLen + width/2 , segLen*2);
            else
                pt += QPoint(segLen/2 , segLen*2);
            p.moveTo(pt);
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 8 :
            pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
            p.moveTo(pt);
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 9 :
            pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
            p.moveTo(pt);
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
#if defined(QT_CHECK_RANGE)
        default :
            qWarning( "QLCDNumber::drawSegment: (%s) Internal error."
                     "  Illegal segment id: %d\n",
                     name( "unnamed" ), segmentNo );
#endif
        }

#undef LINETO
#undef LIGHT
#undef DARK
}
Example #5
0
// UpdatePosition updates the position of the buttons arround the
// selection area. Ignores the sides blocked by the end of the screen.
// When the selection is too small it works on a virtual selection with
// the original in the center.
void ButtonHandler::updatePosition(const QRect &selection) {
    resetRegionTrack();
    const int vecLength = m_vectorButtons.size();
    if (vecLength == 0) {
        return;
    }
    // Copy of the selection area for internal modifications
    m_selection = selection;
    updateBlockedSides();
    ensureSelectionMinimunSize();
    // Indicates the actual button to be moved
    int elemIndicator = 0;

    while (elemIndicator < vecLength) {

        // Add them inside the area when there is no more space
        if (m_allSidesBlocked) {
            positionButtonsInside(elemIndicator);
            break; // the while
        }
        // Number of buttons per row column
        int buttonsPerRow = (m_selection.width() + SEPARATION) / (m_buttonExtendedSize);
        int buttonsPerCol = (m_selection.height() + SEPARATION) / (m_buttonExtendedSize);
        // Buttons to be placed in the corners
        int extraButtons = (vecLength - elemIndicator) -
                (buttonsPerRow + buttonsPerCol) * 2;
        int elemsAtCorners = extraButtons > 4 ? 4 : extraButtons;
        int maxExtra = 2;
        if (m_oneHorizontalBlocked) {
            maxExtra = 1;
        } else if (m_horizontalyBlocked) {
            maxExtra = 0;
        }
        int elemCornersTop = qBound(0, elemsAtCorners, maxExtra);
        elemsAtCorners -= elemCornersTop;
        int elemCornersBotton = qBound(0, elemsAtCorners, maxExtra);

        // Add buttons at the botton of the seletion
        if (!m_blockedBotton) {
            int addCounter = buttonsPerRow + elemCornersBotton;
            // Don't add more than we have
            addCounter = qBound(0, addCounter, vecLength - elemIndicator);
            QPoint center = QPoint(m_selection.center().x(),
                                   m_selection.bottom() + SEPARATION);
            if (addCounter > buttonsPerRow) {
                adjustHorizontalCenter(center);
            }
            // ElemIndicator, elemsAtCorners
            QVector<QPoint> positions = horizontalPoints(center, addCounter, true);
            moveButtonsToPoints(positions, elemIndicator);
        }
        // Add buttons at the right side of the seletion
        if (!m_blockedRight && elemIndicator < vecLength) {
            int addCounter = buttonsPerCol;
            addCounter = qBound(0, addCounter, vecLength - elemIndicator);

            QPoint center = QPoint(m_selection.right() + SEPARATION,
                                   m_selection.center().y());
            QVector<QPoint> positions = verticalPoints(center, addCounter, false);
            moveButtonsToPoints(positions, elemIndicator);
        }
        // Add buttons at the top of the seletion
        if (!m_blockedTop && elemIndicator < vecLength) {
            int addCounter = buttonsPerRow + elemCornersTop;
            addCounter = qBound(0, addCounter, vecLength - elemIndicator);
            QPoint center = QPoint(m_selection.center().x(),
                                   m_selection.top() - m_buttonExtendedSize);
            if (addCounter == 1 + buttonsPerRow) {
                adjustHorizontalCenter(center);
            }
            QVector<QPoint> positions = horizontalPoints(center, addCounter, false);
            moveButtonsToPoints(positions, elemIndicator);
        }
        // Add buttons at the left side of the seletion
        if (!m_blockedLeft && elemIndicator < vecLength) {
            int addCounter = buttonsPerCol;
            addCounter = qBound(0, addCounter, vecLength - elemIndicator);

            QPoint center = QPoint(m_selection.left() - m_buttonExtendedSize,
                                   m_selection.center().y());
            QVector<QPoint> positions = verticalPoints(center, addCounter, true);
            moveButtonsToPoints(positions, elemIndicator);
        }
        // If there are elements for the next cycle, increase the size of the
        // base area
        if (elemIndicator < vecLength && !(m_allSidesBlocked)) {
            expandSelection();
        }
        updateBlockedSides();
    }
}
QPointF ObjectNodeInstance::transformOriginPoint() const
{
    return QPoint();
}
void KexiComboBoxBase::createPopup(bool show)
{
    //kDebug() << show << field() << popup() << m_updatePopupSelectionOnShow;
    if (!field())
        return;
    m_insideCreatePopup = true;
    QWidget* thisWidget = dynamic_cast<QWidget*>(this);
    QWidget *widgetToFocus = internalEditor() ? internalEditor() : thisWidget;

    if (m_reinstantiatePopupOnShow) {
        QWidget *oldPopup = popup();
        setPopup(0);
        delete oldPopup;
    }

    if (!popup()) {
        setPopup(column() ? new KexiComboBoxPopup(thisWidget, *column())
                 : new KexiComboBoxPopup(thisWidget, *field()));
        QObject::connect(popup(), SIGNAL(rowAccepted(KexiDB::RecordData*,int)),
                         thisWidget, SLOT(slotRowAccepted(KexiDB::RecordData*,int)));
        QObject::connect(popup()->tableView(), SIGNAL(itemSelected(KexiDB::RecordData*)),
                         thisWidget, SLOT(slotItemSelected(KexiDB::RecordData*)));

        popup()->setFocusProxy(widgetToFocus);
        popup()->tableView()->setFocusProxy(widgetToFocus);
        popup()->installEventFilter(thisWidget);

        if (origValue().isNull())
            popup()->tableView()->clearSelection();
        else {
            popup()->tableView()->selectRow(0);
            popup()->tableView()->setHighlightedRecord(0);
        }
    }
    if (show && internalEditor() && !internalEditor()->isVisible())
        /*emit*/editRequested();

    QPoint posMappedToGlobal = mapFromParentToGlobal(thisWidget->pos());
    if (posMappedToGlobal != QPoint(-1, -1)) {
//! todo alter the position to fit the popup within screen boundaries
        popup()->hide();
        popup()->move(posMappedToGlobal + QPoint(0, thisWidget->height()));
        //kDebug() << "pos:" << posMappedToGlobal + QPoint(0, thisWidget->height());
        //to avoid flickering: first resize to 0-height, then show and resize back to prev. height
        const int w = popupWidthHint();
        popup()->resize(w, 0);
        if (show) {
            popup()->show();
            //kDebug(44010) << "SHOW!!!";
        }
        popup()->updateSize(w);
        if (m_updatePopupSelectionOnShow) {
            int rowToHighlight = -1;
            KexiDB::LookupFieldSchema *lookupFieldSchema = this->lookupFieldSchema();
            KexiTableViewData *relData = column() ? column()->relatedData() : 0;
            if (lookupFieldSchema) {
                rowToHighlight = rowToHighlightForLookupTable();
            } else if (relData) {
                (void)valueForString(origValue().toString(), &rowToHighlight, 0, 1);
            } else //enum hint
                rowToHighlight = origValue().toInt();

            /*-->*/ m_moveCursorToEndInInternalEditor_enabled = show;
            m_selectAllInInternalEditor_enabled = show;
            m_setValueInInternalEditor_enabled = show;
            if (rowToHighlight == -1) {
                rowToHighlight = qMax(popup()->tableView()->highlightedRecord(), 0);
                setValueInInternalEditor(QVariant());
            }
            popup()->tableView()->selectRow(rowToHighlight);
            popup()->tableView()->setHighlightedRecord(rowToHighlight);
            if (rowToHighlight < popup()->tableView()->rowsPerPage())
                popup()->tableView()->ensureCellVisible(0, -1);

            /*-->*/ m_moveCursorToEndInInternalEditor_enabled = true;
            m_selectAllInInternalEditor_enabled = true;
            m_setValueInInternalEditor_enabled = true;
        }
    }

    if (show) {
        moveCursorToEndInInternalEditor();
        selectAllInInternalEditor();
        widgetToFocus->setFocus();
        popup()->show();
        popup()->raise();
        popup()->repaint();
    }
    m_insideCreatePopup = false;
}
Example #8
0
void BoxCurve::drawBox(QPainter *painter, const QwtScaleMap &xMap,
                       const QwtScaleMap &yMap, double *dat, int size) const {
  const int px = xMap.transform(x(0));
  const int px_min = xMap.transform(x(0) - 0.5);
  const int px_max = xMap.transform(x(0) + 0.5);
  const int box_width = 1 + (px_max - px_min) * b_width / 100;
  const int hbw = box_width / 2;
  const int median =
      yMap.transform(gsl_stats_median_from_sorted_data(dat, 1, size));
  int b_lowerq, b_upperq;
  double sd, se, mean;
  if (w_range == SD || w_range == SE || b_range == SD || b_range == SE) {
    sd = gsl_stats_sd(dat, 1, size);
    se = sd / sqrt((double)size);
    mean = gsl_stats_mean(dat, 1, size);
  }

  if (b_range == SD) {
    b_lowerq = yMap.transform(mean - sd * b_coeff);
    b_upperq = yMap.transform(mean + sd * b_coeff);
  } else if (b_range == SE) {
    b_lowerq = yMap.transform(mean - se * b_coeff);
    b_upperq = yMap.transform(mean + se * b_coeff);
  } else {
    b_lowerq = yMap.transform(
        gsl_stats_quantile_from_sorted_data(dat, 1, size, 1 - 0.01 * b_coeff));
    b_upperq = yMap.transform(
        gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.01 * b_coeff));
  }

  // draw box
  if (b_style == Rect) {
    const QRect r =
        QRect(px - hbw, b_upperq, box_width, b_lowerq - b_upperq + 1);
    painter->fillRect(r, QwtPlotCurve::brush());
    painter->drawRect(r);
  } else if (b_style == Diamond) {
    QPolygon pa(4);
    pa[0] = QPoint(px, b_upperq);
    pa[1] = QPoint(px + hbw, median);
    pa[2] = QPoint(px, b_lowerq);
    pa[3] = QPoint(px - hbw, median);

    painter->setBrush(QwtPlotCurve::brush());
    painter->drawPolygon(pa);
  } else if (b_style == WindBox) {
    const int lowerq =
        yMap.transform(gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.25));
    const int upperq =
        yMap.transform(gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.75));
    QPolygon pa(8);
    pa[0] = QPoint(px + hbw, b_upperq);
    pa[1] = QPoint(int(px + 0.4 * box_width), upperq);
    pa[2] = QPoint(int(px + 0.4 * box_width), lowerq);
    pa[3] = QPoint(px + hbw, b_lowerq);
    pa[4] = QPoint(px - hbw, b_lowerq);
    pa[5] = QPoint(int(px - 0.4 * box_width), lowerq);
    pa[6] = QPoint(int(px - 0.4 * box_width), upperq);
    pa[7] = QPoint(px - hbw, b_upperq);

    painter->setBrush(QwtPlotCurve::brush());
    painter->drawPolygon(pa);
  } else if (b_style == Notch) {
    int j = (int)ceil(0.5 * (size - 1.96 * sqrt((double)size)));
    int k = (int)ceil(0.5 * (size + 1.96 * sqrt((double)size)));
    const int lowerCI = yMap.transform(dat[j]);
    const int upperCI = yMap.transform(dat[k]);

    QPolygon pa(10);
    pa[0] = QPoint(px + hbw, b_upperq);
    pa[1] = QPoint(px + hbw, upperCI);
    pa[2] = QPoint(int(px + 0.25 * hbw), median);
    pa[3] = QPoint(px + hbw, lowerCI);
    pa[4] = QPoint(px + hbw, b_lowerq);
    pa[5] = QPoint(px - hbw, b_lowerq);
    pa[6] = QPoint(px - hbw, lowerCI);
    pa[7] = QPoint(int(px - 0.25 * hbw), median);
    pa[8] = QPoint(px - hbw, upperCI);
    pa[9] = QPoint(px - hbw, b_upperq);

    painter->setBrush(QwtPlotCurve::brush());
    painter->drawPolygon(pa);
  }

  if (w_range) {  // draw whiskers
    const int l = int(0.1 * box_width);
    int w_upperq, w_lowerq;
    if (w_range == SD) {
      w_lowerq = yMap.transform(mean - sd * w_coeff);
      w_upperq = yMap.transform(mean + sd * w_coeff);
    } else if (w_range == SE) {
      w_lowerq = yMap.transform(mean - se * w_coeff);
      w_upperq = yMap.transform(mean + se * w_coeff);
    } else {
      w_lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data(
          dat, 1, size, 1 - 0.01 * w_coeff));
      w_upperq = yMap.transform(
          gsl_stats_quantile_from_sorted_data(dat, 1, size, 0.01 * w_coeff));
    }

    painter->drawLine(px - l, w_lowerq, px + l, w_lowerq);
    painter->drawLine(px - l, w_upperq, px + l, w_upperq);

    if (b_style) {
      if (w_upperq != b_upperq) painter->drawLine(px, w_upperq, px, b_upperq);
      if (w_lowerq != b_lowerq) painter->drawLine(px, w_lowerq, px, b_lowerq);
    } else
      painter->drawLine(px, w_upperq, px, w_lowerq);
  }

  // draw median line
  if (b_style == Notch || b_style == NoBox) return;
  if (b_style == WindBox)
    painter->drawLine(int(px - 0.4 * box_width), median,
                      int(px + 0.4 * box_width), median);
  else
    painter->drawLine(px - hbw, median, px + hbw, median);
}
Example #9
0
//! [1]
bool RotoCanvas::openImage(const QString &fileName)
//! [1] //! [2]
{
    qInfo()<<"RotoCanvas::openImage...";
    QImage loadedImage;
    if (!loadedImage.load(fileName))
        return false;
    this->outputSize = loadedImage.size();
    if (this->loadedFI!=nullptr) {
        delete this->loadedFI;
        this->loadedFI=nullptr;
    }
    this->loadedFI = new QFileInfo(fileName);

    //this->formatString = loadedFI.suffix();
    QSize newSize = loadedImage.size().expandedTo(size());
    //resizeImage(&loadedImage, this->outputSize);
    resizeImage(&panelImage, newSize);  // resizeImage(&)
    fillCheckered(&panelImage);

    /// Load the source frame as originalImage (converting to 32-bit):
    originalImage = QImage(loadedImage.size(), QImage::Format_ARGB32);
    originalImage.fill(qRgba(0,0,0,0));
    QPainter bgPainter(&originalImage);
    bgPainter.drawImage(QPoint(0,0), loadedImage);  // originalImage = loadedImage;

    QPainter displayPainter(&panelImage);
    displayPainter.drawImage(QPoint(0,0), originalImage);
    //isModified = false;
    while (layerPtrs.length()>0) {
        RotoCanvasLayer* thisLayer=layerPtrs.takeLast();
        if (thisLayer!=nullptr) delete thisLayer;
    }
    int frameNumber=getSeqFrameNumber();
    qInfo()<<"frameNumber: "<<frameNumber;
    QString layersPath=getLayersFolderPath(frameNumber,false);
    qInfo()<<"layersPath: "<<layersPath;
    QDir layersDir=QDir(layersPath);
    for (int thisLayerNumber=0; thisLayerNumber<layerCount; thisLayerNumber++) {
        //QString thisLayerPath=layersDir.filePath(QString::number(thisLayerNumber)+"."+RotoCanvas::getSeqFormatString(fileName));
        int thisLayerFrameNumber=-1;
        QString thisLayerPath=getLayerImagePathMostRecent(frameNumber,thisLayerNumber,&thisLayerFrameNumber);
        QFileInfo thisLayerFI=QFileInfo(thisLayerPath);
        if (thisLayerPath!="" && thisLayerFI.exists()) {
            //while (thisLayerFI.exists()) {
            qInfo()<<"Found layer file: "<<thisLayerPath;
            //QImage newImage(loadedImage.size(), QImage::Format_ARGB32);
            //QImage* thisLayerImagePtr=new QImage();
            //thisLayerImagePtr->load(thisLayerPath);
            RotoCanvasLayer* thisLayerPtr=new RotoCanvasLayer();
            thisLayerPtr->frameNumber=thisLayerFrameNumber;
            thisLayerPtr->isModified=false;
            thisLayerPtr->image.load(thisLayerPath);
            //TODO: seek backward to get image from previous keyframe
            layerPtrs.append(thisLayerPtr);
            displayPainter.drawImage(QPoint(0, 0), thisLayerPtr->image);
            //thisLayerNumber++;
            //thisLayerPath=layersDir.filePath(QString::number(thisLayerNumber));
            //thisLayerFI=QFileInfo(thisLayerPath);
            //}
        }
        else {
            layerPtrs.append((RotoCanvasLayer*)nullptr);
            qInfo()<<"No layer file: "<<thisLayerPath;
        }
    }
    //bgPainter.drawImage(QPoint(0,0), displayImage);
    this->selectedLayerIndex=0;
    update();
    return true;
}
Example #10
0
void RoutingDrawWidget::mousePressEvent(QMouseEvent *e)
{
	QScrollView::mousePressEvent(e);
	setFocus();
	
	RoutingWidget *parent = (RoutingWidget *)parentWidget();
	StrGlobal *structure = parent->getStructure();
	
	if (!structure)
		return;
		
	//treba prepocet na zoom a ofset qscrollview - a niekde to pada
	int xp = e->x();
	int yp = e->y();
	
	viewportToContents(xp, yp, xp, yp);
	
	xp = parent->deZoomVal(xp);
	yp = parent->deZoomVal(yp);
	
	RSItemBaseWithType *item;
	
	QPtrList <RSItemBaseWithType> toClear;
	
	if (e->button() == MidButton)
		return;

	if (mode == DragLink)
	{
		QPoint tmpp = mapToGlobal(QPoint(e->x(), e->y()));
		connectLinkDrag(xp, yp, tmpp.x(), tmpp.y());
		return;
	}
		
	// get mode
	if (parent->getWidgetMode() != RoutingWidget::Normal &&
		e->button() == LeftButton)
	{
		parent->putNewObjectAt(xp, yp);
		return;
	}
		
		
	// find item under this point
	bool oneSelected = false;
	bool clearOthers = false;
	
	RSItemBase::RSItemHandle resHandle = RSItemBase::None;
	RSItemBaseWithType *itemToResize = NULL;
	RSItemBaseWithType *itemOn = NULL;
	linkHandle = -1;
	
	for(item = structure->UsedItems.first(); item; item = structure->UsedItems.next())
	{
		bool redraw = false;
		
		if (!oneSelected && item->containsPoint(xp, yp))
		{
			if (!item->flagSelected())
			{
				item->setFlagSelected(true);
				redraw = true;
				clearOthers = true;
			}
			else if (e->state() & Qt::ControlButton)
			{
				item->setFlagSelected(false);
				redraw = true;
			}
			oneSelected = true;
			
			itemOn = item;
			
			// check resize point
			resHandle = item->getHandlePoint(xp, yp);
			if (resHandle == RSItemBase::Other)
			{
				itemToResize = item;
				linkHandle = item->getHandlePointNum(xp, yp);
			}
			else
			{
				linkHandle = -1;			
				if (resHandle != RSItemBase::None)
					itemToResize = item;
			}
		}
		else
		{
			if (item->flagSelected())
				toClear.append(item);
		}
				
		if (redraw)
		{
			this->updateContents(parent->zoomVal(item->x()),
				parent->zoomVal(item->y()),
				parent->zoomVal(item->width()),
				parent->zoomVal(item->height()));
		}
	}
	
	EditMode newMode = None;
	RoutingWidget::MenuMode newMenuMode = RoutingWidget::MenuNone;
	
	parent->itemOn = NULL;
	
	bool doClearOthers = false;
	
	if (e->button() == LeftButton)
	{
		if (!oneSelected)
		{
			// set select mode
			newMode = Select;
		}
		else 
		{
			if (e->state() & Qt::ControlButton)
			{
				newMode = None;
			}
			else
			{
				if (clearOthers)
					doClearOthers = true;
				if (itemToResize)
				{
					resizeItem = itemToResize;
						
					if (linkHandle < 0)
					{
						switch (resHandle)
						{
							case RSItemBase::TopLeft:
								newMode = ResizeTopLeft;
								break;
							case RSItemBase::TopRight:
								newMode = ResizeTopRight;
								break;
							case RSItemBase::BottomLeft:
								newMode = ResizeBottomLeft;
								break;
							case RSItemBase::BottomRight:
								newMode = ResizeBottomRight;
								break;
							default:
								break;
						}
					}
					else
						newMode = HandleMove;
				}
				else if(itemOn->type() != RSItemBaseWithType::Link)
					newMode = Move;
				else
					newMode = None;
			}
		}
	}
	else
	{
		if (!oneSelected)
		{
			newMenuMode = RoutingWidget::MenuNone;
			doClearOthers = true;
		}
		else
		{
			if (clearOthers)
			{
				doClearOthers = true;
			}
				
			if (!doClearOthers && toClear.count() > 0)
				newMenuMode = RoutingWidget::MenuObjects;
			else
			{
				switch (itemOn->type())
				{
					case RSItemBaseWithType::In:
					case RSItemBaseWithType::Out:
					case RSItemBaseWithType::FX:
						newMenuMode = RoutingWidget::MenuIO;
						break;
					case RSItemBaseWithType::Link:
						newMenuMode = RoutingWidget::MenuLink;
						break;
					case RSItemBaseWithType::Patch:
						newMenuMode = RoutingWidget::MenuPatch;
						break;
					default:
						break;
				}
			}
		}
		
		parent->itemOn = itemOn;
		parent->posXOn = xp;
		parent->posYOn = yp;
	}
	
	if (doClearOthers)
	{
		for(item = toClear.first(); item; item = toClear.next())
		{
			item->setFlagSelected(false);
			
			this->updateContents(parent->zoomVal(item->x()),
				parent->zoomVal(item->y()),
				parent->zoomVal(item->width()),
				parent->zoomVal(item->height()));
		}		
	}
	
	if (e->button() == LeftButton)
		mode = newMode;
	else
	{
		QPoint p = mapToGlobal(QPoint(e->x(), e->y()));
		parent->openObjectMenuAt(itemOn, newMenuMode, xp, yp, p.x(), p.y());
	}
	
	selectStartPoint.setX(e->x());
	selectStartPoint.setY(e->y());
	selectEndPoint = selectStartPoint;

}
Example #11
0
void RoutingDrawWidget::mouseReleaseEvent(QMouseEvent *e)
{
	RoutingWidget *parent = (RoutingWidget *)parentWidget();
	StrGlobal *structure = parent->getStructure();
	
	if (!structure)
		return;
		
	if (mode == Select)
	{
		selectEndPoint.setX(e->x());
		selectEndPoint.setY(e->y());
		
		QRect selArea(selectStartPoint, selectEndPoint);
		selArea = selArea.normalize();
		
		// transform
		int xt1;
		int yt1;
		
		int xt2;
		int yt2;
		
		viewportToContents(selArea.x(), selArea.y(), xt1, yt1);
		xt1 = parent->deZoomVal(xt1);
		yt1 = parent->deZoomVal(yt1);
		
		viewportToContents(selArea.right(), selArea.bottom(), xt2, yt2);
		xt2 = parent->deZoomVal(xt2);
		yt2 = parent->deZoomVal(yt2);
		
		// set flag for selected
		QRect selAreaTrans(QPoint(xt1, yt1), QPoint(xt2, yt2));
		
		RSItemBaseWithType *item;		
		for(item = structure->UsedItems.first(); item; item = structure->UsedItems.next() )
		{
			if (selAreaTrans.contains(item->x(), item->y()) &&
				selAreaTrans.contains(item->x() + item->width(), item->y() + item->height()))
			{
				if (!item->flagSelected())
					item->setFlagSelected(true);
			}
			else
			{
				if (!(e->state() & Qt::ControlButton) && item->flagSelected()) 
				{
					item->setFlagSelected(false);
					
					this->updateContents(parent->zoomVal(item->x()),
						parent->zoomVal(item->y()),
						parent->zoomVal(item->width()),
						parent->zoomVal(item->height()));
				}
			}
			
			
		}
		
		//this->updateContents(selArea);
		this->viewport()->update(selArea);
	}
	
	if (mode != DragLink)
		mode = None;
}
void QLCDNumberPrivate::drawSegment(const QPoint &pos, char segmentNo, QPainter &p,
                                    int segLen, bool erase)
{
    Q_Q(QLCDNumber);
    QPoint ppt;
    QPoint pt = pos;
    int width = segLen/5;

    const QPalette &pal = q->palette();
    QColor lightColor,darkColor,fgColor;
    if (erase){
        lightColor = pal.color(q->backgroundRole());
        darkColor  = lightColor;
        fgColor    = lightColor;
    } else {
        lightColor = pal.light().color();
        darkColor  = pal.dark().color();
        fgColor    = pal.color(q->foregroundRole());
    }


#define LINETO(X,Y) addPoint(a, QPoint(pt.x() + (X),pt.y() + (Y)))
#define LIGHT
#define DARK

    if (fill) {
        QPolygon a(0);
        //The following is an exact copy of the switch below.
        //don't make any changes here
        switch (segmentNo) {
        case 0 :
            ppt = pt;
            LIGHT;
            LINETO(segLen - 1,0);
            DARK;
            LINETO(segLen - width - 1,width);
            LINETO(width,width);
            LINETO(0,0);
            break;
        case 1 :
            pt += QPoint(0 , 1);
            ppt = pt;
            LIGHT;
            LINETO(width,width);
            DARK;
            LINETO(width,segLen - width/2 - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 2 :
            pt += QPoint(segLen - 1 , 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width/2 - 2);
            LIGHT;
            LINETO(-width,width);
            LINETO(0,0);
            break;
        case 3 :
            pt += QPoint(0 , segLen);
            ppt = pt;
            LIGHT;
            LINETO(width,-width/2);
            LINETO(segLen - width - 1,-width/2);
            LINETO(segLen - 1,0);
            DARK;
            if (width & 1) {            // adjust for integer division error
                LINETO(segLen - width - 3,width/2 + 1);
                LINETO(width + 2,width/2 + 1);
            } else {
                LINETO(segLen - width - 1,width/2);
                LINETO(width,width/2);
            }
            LINETO(0,0);
            break;
        case 4 :
            pt += QPoint(0 , segLen + 1);
            ppt = pt;
            LIGHT;
            LINETO(width,width/2);
            DARK;
            LINETO(width,segLen - width - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 5 :
            pt += QPoint(segLen - 1 , segLen + 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width - 2);
            LIGHT;
            LINETO(-width,width/2);
            LINETO(0,0);
            break;
        case 6 :
            pt += QPoint(0 , segLen*2);
            ppt = pt;
            LIGHT;
            LINETO(width,-width);
            LINETO(segLen - width - 1,-width);
            LINETO(segLen - 1,0);
            DARK;
            LINETO(0,0);
            break;
        case 7 :
            if (smallPoint)   // if smallpoint place'.' between other digits
                pt += QPoint(segLen + width/2 , segLen*2);
            else
                pt += QPoint(segLen/2 , segLen*2);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 8 :
            pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 9 :
            pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        default :
            qWarning("QLCDNumber::drawSegment: (%s) Illegal segment id: %d\n",
                     q->objectName().toLocal8Bit().constData(), segmentNo);
        }
        // End exact copy
        p.setPen(Qt::NoPen);
        p.setBrush(fgColor);
        p.drawPolygon(a);
        p.setBrush(Qt::NoBrush);

        pt = pos;
    }
#undef LINETO
#undef LIGHT
#undef DARK

#define LINETO(X,Y) p.drawLine(ppt.x(), ppt.y(), pt.x()+(X), pt.y()+(Y)); \
                    ppt = QPoint(pt.x()+(X), pt.y()+(Y))
#define LIGHT p.setPen(lightColor)
#define DARK  p.setPen(darkColor)
    if (shadow)
        switch (segmentNo) {
        case 0 :
            ppt = pt;
            LIGHT;
            LINETO(segLen - 1,0);
            DARK;
            LINETO(segLen - width - 1,width);
            LINETO(width,width);
            LINETO(0,0);
            break;
        case 1 :
            pt += QPoint(0,1);
            ppt = pt;
            LIGHT;
            LINETO(width,width);
            DARK;
            LINETO(width,segLen - width/2 - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 2 :
            pt += QPoint(segLen - 1 , 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width/2 - 2);
            LIGHT;
            LINETO(-width,width);
            LINETO(0,0);
            break;
        case 3 :
            pt += QPoint(0 , segLen);
            ppt = pt;
            LIGHT;
            LINETO(width,-width/2);
            LINETO(segLen - width - 1,-width/2);
            LINETO(segLen - 1,0);
            DARK;
            if (width & 1) {            // adjust for integer division error
                LINETO(segLen - width - 3,width/2 + 1);
                LINETO(width + 2,width/2 + 1);
            } else {
                LINETO(segLen - width - 1,width/2);
                LINETO(width,width/2);
            }
            LINETO(0,0);
            break;
        case 4 :
            pt += QPoint(0 , segLen + 1);
            ppt = pt;
            LIGHT;
            LINETO(width,width/2);
            DARK;
            LINETO(width,segLen - width - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 5 :
            pt += QPoint(segLen - 1 , segLen + 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width - 2);
            LIGHT;
            LINETO(-width,width/2);
            LINETO(0,0);
            break;
        case 6 :
            pt += QPoint(0 , segLen*2);
            ppt = pt;
            LIGHT;
            LINETO(width,-width);
            LINETO(segLen - width - 1,-width);
            LINETO(segLen - 1,0);
            DARK;
            LINETO(0,0);
            break;
        case 7 :
            if (smallPoint)   // if smallpoint place'.' between other digits
                pt += QPoint(segLen + width/2 , segLen*2);
            else
                pt += QPoint(segLen/2 , segLen*2);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 8 :
            pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 9 :
            pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        default :
            qWarning("QLCDNumber::drawSegment: (%s) Illegal segment id: %d\n",
                     q->objectName().toLocal8Bit().constData(), segmentNo);
        }

#undef LINETO
#undef LIGHT
#undef DARK
}
Example #13
0
void Window::init()
{
    m_data = new PrivateData;

    m_data->bar = new QScrollBar(Qt::Vertical, this);
    connect(m_data->bar,
            SIGNAL(valueChanged(int)),
            this,
            SLOT(update()));
    m_data->bar->setEnabled(true);
    m_data->bar->setRange(0, 32678 - 600);
    m_data->bar->setValue(0);
    m_data->bar->move(width() - 30, 0);
    m_data->bar->resize(30, height());




    m_data->renderer = new GraphLib::GraphAggRenderer();
    m_data->interactiveRenderer = new GraphLib::GraphAggInteractiveRenderer((GraphLib::GraphRenderer *)m_data->renderer);
    //
    //m_data->interactiveRenderer->setSize(NULL, 500, 500);
    //

    // 
    QImage *image = new QImage(10.00, 32.678, QImage::Format_ARGB32);
    image->fill(Qt::darkYellow);
    m_data->interactiveRenderer->setSize((void *)image, 
            image->width(), image->height());

    //m_data->renderer->beginRender();

    m_data->interactiveRenderer->fillPixelRect(200, 50, 30, 30, new QColor(Qt::red));

    GraphLib::Rectangle rect1(0, 0, 300, 300);
    m_data->interactiveRenderer->clipRegionAddRect(&rect1);


    resize(800, 600);

    m_data->renderer->beginRender();

    m_data->interactiveRenderer->fillPixelRect(200, 50, 30, 30, new QColor(Qt::red));

    m_data->renderer->setLineWidth(0.3);
    m_data->renderer->drawLine(new GraphLib::Point(10, 10), 
            new GraphLib::Point(30, 50), 
            new QColor(Qt::red));

    m_data->renderer->drawRect(new GraphLib::Point(50, 100), 
            new GraphLib::Point(150, 40201), new QColor(Qt::blue));

    m_data->renderer->fillRect(new GraphLib::Point(80, 50), 
            new GraphLib::Point(100, 70), new QColor(Qt::cyan));

    m_data->renderer->drawEllipse(new GraphLib::Point(50, 100), 
            20, 20, new QColor(0, 1, 0));

    m_data->renderer->fillEllipse(new GraphLib::Point(100, 100), 
            20, 20, new QColor(1, 1, 0));

    GraphLib::Point polyline[] = {QPoint(110, 210), QPoint(120,210), QPoint(130,220)};
    m_data->renderer->drawPolyline(polyline, 
            3, new QColor(1, 1, 0));

    GraphLib::Point polygon[] = {QPoint(110, 310), QPoint(120,310), QPoint(130,320)};
    m_data->renderer->drawPolygon(polygon, 
            3, new QColor(1, 1, 0));

    GraphLib::Point polygon1[] = {QPoint(110, 410), QPoint(120,410), QPoint(130,420)};
    m_data->renderer->fillPolygon(polygon1, 
            3, new QColor(1, 1, 0));

    //for (int i = 100; i < 99900; i+= 20) {
    for (int i = 100; i < 1000; i+= 20) {
        QString str = QString("line %1").arg(i);
        m_data->renderer->drawString(str, 
                new GraphLib::Point(20, i), 0, new QColor(1, 1, 0));
    }



    GraphLib::GraphAggRenderer *r = m_data->renderer;
    r->beginPath();
    r->moveTo(30, 30);
    r->lineTo(500, 500);

    r->moveTo(200, 200.2);
    r->lineTo(400, 200.2);

    r->moveTo(200, 100);
    r->lineTo(400, 100);


    r->moveTo(50.5, 50);
    r->lineTo(50.5, 200);
    r->setLineWidth(0.5);
    r->endPath();



    m_data->renderer->endRender();

}
Example #14
0
bool CertWizard::validateCurrentPage() {
	if (currentPage() == qwpNew) {
		QRegExp ereg(QLatin1String("(^$)|((.+)@(.+))"), Qt::CaseInsensitive, QRegExp::RegExp2);
		if (!ereg.exactMatch(qleEmail->text())) {
			qlError->setText(tr("Unable to validate email.<br />Enter a valid (or blank) email to continue."));
			qwpNew->setComplete(false);
			return false;
		} else {
			kpNew = generateNewCert(qleName->text(), qleEmail->text());
			
			if (! validateCert(kpNew)) {
				qlError->setText(tr("There was an error generating your certificate.<br />Please try again."));
				return false;
			}
		}
	}
	if (currentPage() == qwpExport) {
		QByteArray qba = exportCert(kpNew);
		if (qba.isEmpty()) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("Your certificate and key could not be exported to PKCS#12 format. There might be an error in your certificate."), qleExportFile);
			return false;
		}
		QFile f(qleExportFile->text());
		if (! f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Unbuffered)) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be opened for writing. Please use another file."), qleExportFile);
			return false;
		}
		if (! f.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file's permissions could not be set. No certificate and key has been written. Please use another file."), qleExportFile);
			return false;
		}
		qint64 written = f.write(qba);
		f.close();
		if (written != qba.length()) {
			QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be written successfully. Please use another file."), qleExportFile);
			return false;
		}
	}
	if (currentPage() == qwpImport) {
		QFile f(qleImportFile->text());
		if (! f.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {
			QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be opened for reading. Please use another file."), qleImportFile);
			return false;
		}
		QByteArray qba = f.readAll();
		f.close();
		if (qba.isEmpty()) {
			QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file is empty or could not be read. Please use another file."), qleImportFile);
			return false;
		}
		QPair<QList<QSslCertificate>, QSslKey> imp = importCert(qba, qlePassword->text());
		if (! validateCert(imp)) {
			QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file did not contain a valid certificate and key. Please use another file."), qleImportFile);
			return false;
		}
		kpNew = imp;
	}
	if (currentPage() == qwpFinish) {
		g.s.kpCertificate = kpNew;
	}
	return QWizard::validateCurrentPage();
}
Example #15
0
 void resizeEvent(QResizeEvent *event) {
     if (scene())
         scene()->setSceneRect(QRect(QPoint(0, 0), event->size()));
     QGraphicsView::resizeEvent(event);
 }
Example #16
0
void ChromeClientQt::delegatedScrollRequested(const IntPoint& point)
{
    QPoint currentPosition(m_webPage->mainFrame()->scrollPosition());
    emit m_webPage->scrollRequested(point.x() - currentPosition.x(), point.y() - currentPosition.y(), QRect(QPoint(0, 0), m_webPage->viewportSize()));
}
Example #17
0
void SpeedLabel::showSpeedMenu( QPoint pos )
{
    speedControlMenu->exec( QCursor::pos() - pos
                            + QPoint( -70 + width()/2, height() ) );
}
Example #18
0
void QUnifiedToolbarSurface::insertToolbar(QWidget *toolbar, const QPoint &offset)
{
    setGeometry(QRect(QPoint(0, 0), QSize(offset.x() + toolbar->width(), 100))); // FIXME
    recursiveRedirect(toolbar, toolbar, offset);
}
Example #19
0
void ShaderEffect::updateRenderTargets()
{
    if (!m_changed)
        return;

    m_changed = false;

    int count = m_renderTargets.count();
    for (int i = 0; i < count; i++) {
        if (m_renderTargets[i]->isLive() || m_renderTargets[i]->isDirtyTexture()) {
            m_renderTargets[i]->updateBackbuffer();
            ShaderEffectBuffer* target = m_renderTargets[i]->fbo();
            if (target && target->isValid() && target->width() > 0 && target->height() > 0) {
                QPainter p(target);
                p.setCompositionMode(QPainter::CompositionMode_Clear);
                p.fillRect(QRect(QPoint(0, 0), target->size()), Qt::transparent);
                p.setCompositionMode(QPainter::CompositionMode_SourceOver);

                QRectF sourceRect = m_renderTargets[i]->sourceRect();
                QSize textureSize = m_renderTargets[i]->textureSize();

                qreal yflip = m_renderTargets[i]->isMirrored() ? -1.0 : 1.0; // flip y to match scenegraph, it also flips texturecoordinates
                qreal xscale = 1.0;
                qreal yscale = 1.0 * yflip;

                qreal leftMargin = 0.0;
                qreal rightMargin = 0.0;
                qreal topMargin = 0.0;
                qreal bottomMargin = 0.0;

                qreal width = m_renderTargets[i]->sourceItem()->width();
                qreal height = m_renderTargets[i]->sourceItem()->height();

                if (!sourceRect.isEmpty()) {
                    leftMargin = -sourceRect.left();
                    rightMargin = sourceRect.right() - width;
                    topMargin = -sourceRect.top();
                    bottomMargin = sourceRect.bottom() - height;
                }

                if ((width + leftMargin + rightMargin) > 0 && (height + topMargin + bottomMargin) > 0) {
                    if (!textureSize.isEmpty()) {
                        qreal textureWidth = textureSize.width();
                        qreal textureHeight = textureSize.height();

                        xscale = width / (width + leftMargin + rightMargin);
                        yscale = height / (height + topMargin + bottomMargin);

                        p.translate(textureWidth / 2, textureHeight / 2);
                        p.scale(xscale, yscale * yflip);
                        p.translate(-textureWidth / 2, -textureHeight / 2);
                        p.scale(textureWidth / width, textureHeight / height);
                    } else {
                        xscale = width / (width + leftMargin + rightMargin);
                        yscale = height / (height + topMargin + bottomMargin);

                        p.translate(width / 2, height / 2);
                        p.scale(xscale, yscale * yflip);
                        p.translate(-width / 2, -height / 2);
                    }
                }

                drawSource(&p);
                p.end();
                m_renderTargets[i]->markSceneGraphDirty();
            }
        }
    }
}
Example #20
0
QList<QgsMapToolIdentify::IdentifyResult> QgsMapToolIdentify::identify( int x, int y, IdentifyMode mode, QList<QgsMapLayer*> layerList, LayerType layerType )
{
  QList<IdentifyResult> results;

  mLastPoint = mCanvas->getCoordinateTransform()->toMapCoordinates( x, y );
  mLastExtent = mCanvas->extent();
  mLastMapUnitsPerPixel = mCanvas->mapUnitsPerPixel();

  if ( mode == DefaultQgsSetting )
  {
    QSettings settings;
    mode = static_cast<IdentifyMode>( settings.value( "/Map/identifyMode", 0 ).toInt() );
  }

  if ( mode == LayerSelection )
  {
    QList<IdentifyResult> results = identify( x, y, TopDownAll, layerList, layerType );
    QPoint globalPos = mCanvas->mapToGlobal( QPoint( x + 5, y + 5 ) );
    return mIdentifyMenu->exec( results, globalPos );
  }
  else if ( mode == ActiveLayer && layerList.isEmpty() )
  {
    QgsMapLayer *layer = mCanvas->currentLayer();

    if ( !layer )
    {
      emit identifyMessage( tr( "No active layer. To identify features, you must choose an active layer." ) );
      return results;
    }

    QApplication::setOverrideCursor( Qt::WaitCursor );

    identifyLayer( &results, layer, mLastPoint, mLastExtent, mLastMapUnitsPerPixel, layerType );
  }
  else
  {
    QApplication::setOverrideCursor( Qt::WaitCursor );

    QStringList noIdentifyLayerIdList = QgsProject::instance()->readListEntry( "Identify", "/disabledLayers" );

    int layerCount;
    if ( layerList.isEmpty() )
      layerCount = mCanvas->layerCount();
    else
      layerCount = layerList.count();


    for ( int i = 0; i < layerCount; i++ )
    {

      QgsMapLayer *layer;
      if ( layerList.isEmpty() )
        layer = mCanvas->layer( i );
      else
        layer = layerList.value( i );

      emit identifyProgress( i, mCanvas->layerCount() );
      emit identifyMessage( tr( "Identifying on %1..." ).arg( layer->name() ) );

      if ( noIdentifyLayerIdList.contains( layer->id() ) )
        continue;

      if ( identifyLayer( &results, layer,  mLastPoint, mLastExtent, mLastMapUnitsPerPixel, layerType ) )
      {
        if ( mode == TopDownStopAtFirst )
          break;
      }
    }

    emit identifyProgress( mCanvas->layerCount(), mCanvas->layerCount() );
    emit identifyMessage( tr( "Identifying done." ) );
  }

  QApplication::restoreOverrideCursor();

  return results;
}
/*!
    \reimp
 */
void QxtSpanSlider::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);
    QStylePainter painter(this);

    // groove & ticks
    QStyleOptionSlider opt;
    qxt_d().initStyleOption(&opt);
    opt.sliderValue = 0;
    opt.sliderPosition = 0;
    opt.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderTickmarks;
    painter.drawComplexControl(QStyle::CC_Slider, opt);

    // handle rects
    opt.sliderPosition = qxt_d().lowerPos;
    const QRect lr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
    const int lrv  = qxt_d().pick(lr.center());
    opt.sliderPosition = qxt_d().upperPos;
    const QRect ur = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
    const int urv  = qxt_d().pick(ur.center());

    // span
    const QPoint c = QRect(lr.center(), ur.center()).center();
    if(lrv <= urv)
    {
        QRect spanRect;
        if (orientation() == Qt::Horizontal)
            spanRect = QRect(QPoint(lrv, c.y() - 2), QPoint(urv, c.y() + 1));
        else
            spanRect = QRect(QPoint(c.x() - 2, lrv), QPoint(c.x() + 1, urv));
        qxt_d().drawSpan(&painter, spanRect);
    }
    else
    {
        QRect groove = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this);
        QRect spanRect1, spanRect2;
        if (orientation() == Qt::Horizontal)
        {
            spanRect1 = QRect(QPoint(groove.left() + 2, c.y() - 2), QPoint(urv, c.y() + 1));
            spanRect2 = QRect(QPoint(lrv, c.y() - 2), QPoint(groove.right() - 3, c.y() + 1));
        }
        else
        {
            spanRect1 = QRect(QPoint(c.x() - 2, groove.top() + 2), QPoint(c.x() + 1, urv));
            spanRect2 = QRect(QPoint(c.x() - 2, lrv), QPoint(c.x() + 1, groove.bottom() - 3));
        }
        qxt_d().drawSpan(&painter, spanRect1);
        qxt_d().drawSpan(&painter, spanRect2);
    }

    // handles
    switch (qxt_d().lastPressed)
    {
    case QxtSpanSliderPrivate::LowerHandle:
        qxt_d().drawHandle(&painter, QxtSpanSliderPrivate::UpperHandle);
        qxt_d().drawHandle(&painter, QxtSpanSliderPrivate::LowerHandle);
        break;
    case QxtSpanSliderPrivate::UpperHandle:
    default:
        qxt_d().drawHandle(&painter, QxtSpanSliderPrivate::LowerHandle);
        qxt_d().drawHandle(&painter, QxtSpanSliderPrivate::UpperHandle);
        break;
    }
}
Example #22
0
// QRectF contentsRect() const public
void tst_QGraphicsLayoutItem::contentsRect()
{
    SubQGraphicsLayoutItem layoutItem;
    QRectF f = layoutItem.contentsRect();
    QCOMPARE(f, QRectF(QPoint(), QSizeF(0, 0)));
}
bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
{
    switch(m->message) {
    case MYWM_NOTIFYICON:
        {
            int message = 0;
            QPoint gpos;

            if (version == NOTIFYICON_VERSION_4) {
                Q_ASSERT(q_uNOTIFYICONID == HIWORD(m->lParam));
                message = LOWORD(m->lParam);
                gpos = QPoint(GET_X_LPARAM(m->wParam), GET_Y_LPARAM(m->wParam));
            } else {
                Q_ASSERT(q_uNOTIFYICONID == m->wParam);
                message = m->lParam;
                gpos = QCursor::pos();
            }

            switch (message) {
            case NIN_SELECT:
            case NIN_KEYSELECT:
                if (ignoreNextMouseRelease)
                    ignoreNextMouseRelease = false;
                else 
                    emit q->activated(QSystemTrayIcon::Trigger);
                break;

            case WM_LBUTTONDBLCLK:
                ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse 
                                               // release we must ignore it
                emit q->activated(QSystemTrayIcon::DoubleClick);
                break;

            case WM_CONTEXTMENU:
                if (q->contextMenu()) {
                    q->contextMenu()->popup(gpos);
                    q->contextMenu()->activateWindow();
                }
                emit q->activated(QSystemTrayIcon::Context);
                break;

            case NIN_BALLOONUSERCLICK:
                emit q->messageClicked();
                break;

            case WM_MBUTTONUP:
                emit q->activated(QSystemTrayIcon::MiddleClick);
                break;

            default:
                break;
            }
            break;
        }
    default:
        if (m->message == MYWM_TASKBARCREATED)
            trayMessage(NIM_ADD);
        else
            return QWidget::winEvent(m, result);
        break;
    }
    return 0;
}
Example #24
0
void ItemsViewDelegate::updateItemWidgets(const QList<QWidget *> widgets,
        const QStyleOptionViewItem &option,
        const QPersistentModelIndex &index) const
{
    const KNSCore::ItemsModel *model = qobject_cast<const KNSCore::ItemsModel *>(index.model());
    if (!model) {
        qCDebug(KNEWSTUFF) << "WARNING - INVALID MODEL!";
        return;
    }

    KNSCore::EntryInternal entry = index.data(Qt::UserRole).value<KNSCore::EntryInternal>();

    // setup the install button
    int margin = option.fontMetrics.height() / 2;
    int right = option.rect.width();

    QToolButton *installButton = qobject_cast<QToolButton *>(widgets.at(DelegateInstallButton));
    if (installButton != 0) {

        if (installButton->menu()) {
            QMenu *buttonMenu = installButton->menu();
            buttonMenu->clear();
            installButton->setMenu(0);
            buttonMenu->deleteLater();
        }

        bool installable = false;
        bool enabled = true;
        QString text;
        QIcon icon;

        switch (entry.status()) {
        case Entry::Installed:
            text = i18n("Uninstall");
            icon = m_iconDelete;
            break;
        case Entry::Updateable:
            text = i18n("Update");
            icon = m_iconUpdate;
            installable = true;
            break;
        case Entry::Installing:
            text = i18n("Installing");
            enabled = false;
            icon = m_iconUpdate;
            break;
        case Entry::Updating:
            text = i18n("Updating");
            enabled = false;
            icon = m_iconUpdate;
            break;
        case Entry::Downloadable:
            text = i18n("Install");
            icon = m_iconInstall;
            installable = true;
            break;
        case Entry::Deleted:
            text = i18n("Install Again");
            icon = m_iconInstall;
            installable = true;
            break;
        default:
            text = i18n("Install");
        }
        installButton->setText(text);
        installButton->setEnabled(enabled);
        installButton->setIcon(icon);
        if (installable && entry.downloadLinkCount() > 1) {
            QMenu *installMenu = new QMenu(installButton);
            foreach (const KNSCore::EntryInternal::DownloadLinkInformation &info, entry.downloadLinkInformationList()) {
                QString text = info.name;
                if (!info.distributionType.trimmed().isEmpty()) {
                    text + " (" + info.distributionType.trimmed() + ')';
                }
                QAction *installAction = installMenu->addAction(m_iconInstall, text);
                installAction->setData(QPoint(index.row(), info.id));
            }
            installButton->setMenu(installMenu);
        }
    }
Example #25
0
QPoint FormWindowBase::grid() const
{
    return QPoint(m_d->m_grid.deltaX(), m_d->m_grid.deltaY());
}
Example #26
0
// -----------------------------------------------------------
// Is called if user clicked on component text of if return is
// pressed in the component text QLineEdit.
// In "view->MAx3" is the number of the current property.
void QucsApp::slotApplyCompText()
{
  QString s;
  QFont f = QucsSettings.font;
  Schematic *Doc = (Schematic*)DocumentTab->currentPage();
  f.setPointSizeFloat( Doc->Scale * float(f.pointSize()) );
  editText->setFont(f);

  Property  *pp = 0;
  Component *pc = (Component*)view->focusElement;
  if(!pc) return;  // should never happen
  view->MAx1 = pc->cx + pc->tx;
  view->MAy1 = pc->cy + pc->ty;

  int z, n=0;  // "n" is number of property on screen
  pp = pc->Props.first();
  for(z=view->MAx3; z>0; z--) {  // calculate "n"
    if(!pp) {  // should never happen
      editText->setHidden(true);
      return;
    }
    if(pp->display) n++;   // is visible ?
    pp = pc->Props.next();
  }

  pp = 0;
  if(view->MAx3 > 0)  pp = pc->Props.at(view->MAx3-1); // current property
  else s = pc->Name;

  if(!editText->isHidden()) {   // is called the first time ?
    // no -> apply value to current property
    if(view->MAx3 == 0) {   // component name ?
      Component *pc2;
      if(!editText->text().isEmpty())
        if(pc->Name != editText->text()) {
          for(pc2 = Doc->Components->first(); pc2!=0; pc2 = Doc->Components->next())
            if(pc2->Name == editText->text())
              break;  // found component with the same name ?
          if(!pc2) {
            pc->Name = editText->text();
            Doc->setChanged(true, true);  // only one undo state
          }
        }
    }
    else if(pp) {  // property was applied
      if(pp->Value != editText->text()) {
        pp->Value = editText->text();
        Doc->recreateComponent(pc);  // because of "Num" and schematic symbol
        Doc->setChanged(true, true); // only one undo state
      }
    }

    n++;     // next row on screen
    (view->MAx3)++;  // next property
    pp = pc->Props.at(view->MAx3-1);  // search for next property

    Doc->viewport()->update();
    view->drawn = false;

    if(!pp) {     // was already last property ?
      editText->setHidden(true);
      return;
    }


    while(!pp->display) {  // search for next visible property
      (view->MAx3)++;  // next property
      pp = pc->Props.next();
      if(!pp) {     // was already last property ?
        editText->setHidden(true);
        return;
      }
    }
  }

  // avoid seeing the property text behind the line edit
  if(pp)  // Is it first property or component name ?
    s = pp->Value;
  editText->setMinimumWidth(editText->fontMetrics().width(s)+4);


  Doc->contentsToViewport(int(Doc->Scale * float(view->MAx1 - Doc->ViewX1)),
			 int(Doc->Scale * float(view->MAy1 - Doc->ViewY1)),
			 view->MAx2, view->MAy2);
  editText->setReadOnly(false);
  if(pp) {  // is it a property ?
    s = pp->Value;
    view->MAx2 += editText->fontMetrics().width(pp->Name+"=");
    if(pp->Description.find('[') >= 0)  // is selection list ?
      editText->setReadOnly(true);
    Expr_CompProp.setPattern("[^\"]*");
    if(!pc->showName) n--;
  }
  else   // it is the component name
    Expr_CompProp.setPattern("[\\w_]+");
  Val_CompProp.setRegExp(Expr_CompProp);
  editText->setValidator(&Val_CompProp);

  z = editText->fontMetrics().lineSpacing();
  view->MAy2 += n*z;
  editText->setText(s);
  editText->setPaletteBackgroundColor(QucsSettings.BGColor);
  editText->setFocus();
  editText->selectAll();
  editText->reparent(Doc->viewport(), 0, QPoint(view->MAx2, view->MAy2), true);
}
Example #27
0
// Draws a cached pixmap with shadow
void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect,
                                     QPainter *p, QIcon::Mode iconMode, int radius, const QColor &color, const QPoint &offset)
{
    QPixmap cache;
    QString pixmapName = QString::fromLatin1("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg(rect.height());

    if (!QPixmapCache::find(pixmapName, cache)) {
        QPixmap px = icon.pixmap(rect.size());
        cache = QPixmap(px.size() + QSize(radius * 2, radius * 2));
        cache.fill(Qt::transparent);

        QPainter cachePainter(&cache);
        if (iconMode == QIcon::Disabled) {
            QImage im = px.toImage().convertToFormat(QImage::Format_ARGB32);
            for (int y=0; y<im.height(); ++y) {
                QRgb *scanLine = (QRgb*)im.scanLine(y);
                for (int x=0; x<im.width(); ++x) {
                    QRgb pixel = *scanLine;
                    char intensity = qGray(pixel);
                    *scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel));
                    ++scanLine;
                }
            }
            px = QPixmap::fromImage(im);
        }

        // Draw shadow
        QImage tmp(px.size() + QSize(radius * 2, radius * 2 + 1), QImage::Format_ARGB32_Premultiplied);
        tmp.fill(Qt::transparent);

        QPainter tmpPainter(&tmp);
        tmpPainter.setCompositionMode(QPainter::CompositionMode_Source);
        tmpPainter.drawPixmap(QPoint(radius, radius), px);
        tmpPainter.end();

        // blur the alpha channel
        QImage blurred(tmp.size(), QImage::Format_ARGB32_Premultiplied);
        blurred.fill(Qt::transparent);
        QPainter blurPainter(&blurred);
        qt_blurImage(&blurPainter, tmp, radius, false, true);
        blurPainter.end();

        tmp = blurred;

        // blacken the image...
        tmpPainter.begin(&tmp);
        tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        tmpPainter.fillRect(tmp.rect(), color);
        tmpPainter.end();

        tmpPainter.begin(&tmp);
        tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        tmpPainter.fillRect(tmp.rect(), color);
        tmpPainter.end();

        // draw the blurred drop shadow...
        cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp);

        // Draw the actual pixmap...
        cachePainter.drawPixmap(QPoint(radius, radius) + offset, px);
        QPixmapCache::insert(pixmapName, cache);
    }

    QRect targetRect = cache.rect();
    targetRect.moveCenter(rect.center());
    p->drawPixmap(targetRect.topLeft() - offset, cache);
}
Example #28
0
bool PolyQtAnnotation::contains(const QPointF & point) const {
  if (shape().controlPointRect().contains(point)) {
    QPointF imgPoint = this->mapToScene(point) / _scale;
    double curSelectionSensitivity = (_selectionSensitivity * _lineAnnotationSelectedThickness / _currentLoD);
    double curSelectionSensitivitySquared = curSelectionSensitivity * curSelectionSensitivity;
    double imgX = imgPoint.x();
    double imgY = imgPoint.y();
    std::vector<Point> coords = _annotation->getCoordinates();
    double minDist = std::numeric_limits<double>::max();
    _lastClickedFirstCoordinateIndex = -1;
    _lastClickedSecondCoordinateIndex = -1;

    // Quickly check if a seed point was hit
    for (unsigned int i = 0; i < coords.size(); ++i) {
      Point pt1 = coords[i];
      double coord1X = pt1.getX(); double coord1Y = pt1.getY();
      double distSquared = pow(imgX - coord1X, 2) + pow(imgY - coord1Y, 2);
      if (distSquared < curSelectionSensitivitySquared && distSquared < minDist) {
        _lastClickedFirstCoordinateIndex = i;
        _lastClickedSecondCoordinateIndex = -1;
        _lastClickedLinePoint = QPointF();
        minDist = distSquared;
      }
    }
    if (_lastClickedFirstCoordinateIndex >= 0) {
      return true;
    }

    minDist = std::numeric_limits<double>::max();
    // If not, check if a line was hit
    std::vector<QPointF> polyInImgCoords;
    unsigned int polyIndex = 0;
    if (_type == "spline") {
      for (QPolygonF::const_iterator it = _polys.begin(); it != _polys.end(); ++it) {
        polyInImgCoords.push_back(this->mapToScene(*it) / _scale);
      }
    }
    for (unsigned int i = 0; i < coords.size(); ++i) {
      Point pt1 = coords[i];
      Point pt2 = i == coords.size() -1 ? coords[0] : coords[i + 1];
      double coord1X = pt1.getX(); double coord1Y = pt1.getY();
      double coord2X = pt2.getX(); double coord2Y = pt2.getY();
      QRectF hitbox(imgX - curSelectionSensitivity / 2., imgY - curSelectionSensitivity / 2., curSelectionSensitivity * 2., curSelectionSensitivity * 2.);
      QRectF lineBox(QPointF(std::min(coord1X, coord2X), std::max(coord1Y, coord2Y)), QPointF(std::max(coord1X, coord2X), std::min(coord1Y, coord2Y)));       
      if (hitbox.intersects(lineBox)) {
        if (_type == "spline") {
          for (unsigned int j = 0; j < polyInImgCoords.size(); ++j) {
            QPointF polyPt1 = polyInImgCoords[polyIndex];
            QPointF polyPt2 = polyIndex == polyInImgCoords.size() - 1 ? polyInImgCoords[0] : polyInImgCoords[polyIndex + 1];
            if (QPoint(polyPt1.x(), polyPt1.y()) == QPoint(coord2X, coord2Y)) {
              break;
            }
            double polyCoord1X = polyPt1.x(); double polyCoord1Y = polyPt1.y();
            double polyCoord2X = polyPt2.x(); double polyCoord2Y = polyPt2.y();
            QRectF polyBox(QPointF(std::min(polyCoord1X, polyCoord2X), std::max(polyCoord1Y, polyCoord2Y)), QPointF(std::max(polyCoord1X, polyCoord2X), std::min(polyCoord1Y, polyCoord2Y)));
            if (hitbox.intersects(polyBox)) {
              double lineLengthSquared = pow(polyCoord1X - polyCoord2X, 2) + pow(polyCoord1Y - polyCoord2Y, 2);
              double t = ((imgX - polyCoord2X) * (polyCoord1X - polyCoord2X) + (imgY - polyCoord2Y) * (polyCoord1Y - polyCoord2Y)) / lineLengthSquared;
              double projX = polyCoord2X + t * (polyCoord1X - polyCoord2X);
              double projY = polyCoord2Y + t * (polyCoord1Y - polyCoord2Y);
              double distSquared = pow(imgX - projX, 2) + pow(imgY - projY, 2);
              if (distSquared < curSelectionSensitivitySquared && distSquared < minDist) {
                _lastClickedFirstCoordinateIndex = i;
                _lastClickedSecondCoordinateIndex = i + 1 == coords.size() ? 0 : i + 1;
                _lastClickedLinePoint = QPointF(projX, projY);
              }
            }
            ++polyIndex;
          }
        }
        else {
          double lineLengthSquared = pow(coord1X - coord2X, 2) + pow(coord1Y - coord2Y, 2);
          double t = ((imgX - coord2X) * (coord1X - coord2X) + (imgY - coord2Y) * (coord1Y - coord2Y)) / lineLengthSquared;
          double projX = coord2X + t * (coord1X - coord2X);
          double projY = coord2Y + t * (coord1Y - coord2Y);
          double distSquared = pow(imgX - projX, 2) + pow(imgY - projY, 2);
          if (distSquared < curSelectionSensitivitySquared && distSquared < minDist) {
            _lastClickedFirstCoordinateIndex = i;
            _lastClickedSecondCoordinateIndex = i + 1 == coords.size() ? 0 : i + 1;
            _lastClickedLinePoint = QPointF(projX, projY);
          }
        }
      }
    }
    if (_lastClickedFirstCoordinateIndex < 0) {
      return false;
    }
    else {
      return true;
    }
  }
  return false;
}
Example #29
0
/*!
    Wrapper for QPainter::drawText()
*/
void QwtPainter::drawText(QPainter *painter, int x, int y, 
        const QString &text)
{
    drawText(painter, QPoint(x, y), text);
}
Example #30
0
QPoint Settings::getWindowPos(const QString &windowName)
{
    return value(windowName+"/pos", QPoint(0, 0)).toPoint();
}