void ImageLoader::run() { QString fn = m_url.toLocalFile(); int pos = fn.lastIndexOf('.'); QString ext; if (pos != -1) ext = fn.mid(pos).toUpper(); if (ext.isEmpty() || !QImageReader::supportedImageFormats().contains(ext.toLocal8Bit())) ext = QString(); QFile f(fn); if (!f.open(QIODevice::ReadOnly)) { qWarning("Could not read: %s", qPrintable(m_url.path())); return; } QByteArray bytes; while (!f.atEnd()) { QThread::yieldCurrentThread(); bytes.append(f.read(1024)); } QThread::yieldCurrentThread(); QImage im = ext.isEmpty() ? QImage::fromData(bytes) : QImage::fromData(bytes, qPrintable(ext)); if (im.isNull()) return; QString p = m_url.path(); p = p.section("/", -1); int max = qMax(im.width(), im.height()); QImage frm; if (max <= 64) frm = QImage(QSize(64, 64), QImage::Format_ARGB32); else if (max <= 128) frm = QImage(QSize(128, 128), QImage::Format_ARGB32); else if (max <= 256) frm = QImage(QSize(256, 256), QImage::Format_ARGB32); else if (max <= 512) frm = QImage(QSize(512, 512), QImage::Format_ARGB32); else frm = QImage(QSize(1024, 1024), QImage::Format_ARGB32); frm.fill(qRgba(0, 0, 0, 0)); QPainter ptr; ptr.begin(&frm); ptr.setBackgroundMode(Qt::TransparentMode); QRect r; if (max > 1024) { if (max == im.width()) { float h = float(1024) * float(im.height()) / float(im.width()); r.setSize(QSize(1024, h)); } else { float w = float(1024) * float(im.width()) / float(im.height()); r.setSize(QSize(w, 1024)); } } else { r.setSize(im.size()); } int left = (frm.width() - r.width()) / 2; int top = (frm.height() - r.height()) / 2; r.moveTopLeft(QPoint(left, top)); QThread::yieldCurrentThread(); ptr.drawImage(r, im); ptr.end(); emit imageLoaded(frm); }
bool setDegu::paint(QImage *image){ /* int w = m_data->fgImage->width(), h = m_data->fgImage->height(); cv::Mat f(h, w, CV_8UC1); uchar *fg_p = m_data->fgImage->bits(); int bl = m_data->fgImage->bytesPerLine(); memcpy(f.data, fg_p, h*bl); cv::Mat border_aux(f.size(), CV_8UC1); cv::Canny(f,border_aux, 50,100, 3); std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::Mat border_copy(border_aux.size(), CV_8UC1); border_aux.copyTo(border_copy); cv::findContours(border_copy, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) ); std::vector<cv::Point> big_contour; std::vector<cv::Point> hull; if(contours.size() > 0) { //Group found contours in one big contour for(int i=0;i<contours.size(); i++) { if(hierarchy[i][2] < 0) { // No parent, so it's parent if(big_contour.empty()) big_contour = contours[i]; else big_contour.insert( big_contour.end(), contours[i].begin(), contours[i].end()); } } //Get initial convex hull cv::convexHull( big_contour, hull, false ); } else { return true; } if(hull.size() == 0) { return true; } //cv::erode(aux, aux, element); //cv::dilate(aux, aux, element,cv::Point(-1,-1),2); //cv::erode(aux, aux, element); SpHullModel newHull(new HullModel()); newHull->local_hull = hull; newHull->off_x = 0; newHull->off_y = 0; //newHull->off_x = j0; //newHull->off_y = i0; //newHull->id = (*it)->mobile_id; newHull->id = NULL; int w0 = m_data->fgImage->width(), h0 = m_data->fgImage->height(); //Get principal/minor axis std::vector<cv::Point2f> data_aux(h0*w0); float mean_x = 0, mean_y = 0; int count = 0; for(int i=0; i<h0; i++) for(int j=0; j<w0; j++) if(cv::pointPolygonTest(hull, cv::Point2f(j, i), true) > - 1) { data_aux[count++] = cv::Point2f(j, i); mean_x += j; mean_y += i; } //data_aux.resize(count); //cv::Mat data(2, count, CV_32FC1, &data_aux.front()); cv::Mat data(2, count, CV_32FC1); cv::Point2f x; for(int i=0; i<count; i++) { data.at<float>(0,i) = data_aux[i].x; data.at<float>(1,i) = data_aux[i].y; } //cv::Mat data(); mean_x /= count; mean_y /= count; cv::Mat mean(2, 1, CV_32FC1); mean.at<float>(0) = mean_x; mean.at<float>(1) = mean_y; //2. perform PCA cv::PCA pca(data, mean, CV_PCA_DATA_AS_COL, 1); //result is contained in pca.eigenvectors (as row vectors) //std::cout << pca.eigenvectors << std::endl; //3. get angle of principal axis float dx = pca.eigenvectors.at<float>(0, 0), dy = pca.eigenvectors.at<float>(0, 1), scale = 40.0; cv::Point3f rline; cv::Point2f r1, r2; //Get line general form from principal component getGeneralLineForm(cv::Point2f(mean_x, mean_y), cv::Point2f(mean_x + dx*scale, mean_y + dy*scale), rline); //Get segment from line int n1, n2; getContourToLineIntersection(hull, rline, r1, r2, &n1, &n2); //Get pixel intersections for normals std::vector< segment2D<float> > &segs = newHull->segs; std::vector< segment2D<float> > &hull_segs = newHull->hull_segs; cv::Rect roi; roi.x = 0; roi.y = 0; roi.width = w0; roi.height = h0; cv::Mat aux(f, roi); //Get segments of movement normal to principal axis. Also reorders r1 and r2 in //coherence with segments order getNormalIntersections(aux, roi, hull, r1, r2, n1, n2, dx, dy, segs, hull_segs); newHull->axis1 = r1; newHull->axis2 = r2; */ //Set new representation //m_data->hulls.push_back(newHull); //inactivo temporalmente std::map<QString,DeguTrackingModel *>::iterator modeloMain; modeloMain= m_data->modelsToFollow.find("main"); if(modeloMain!=m_data->modelsToFollow.end()){ }else return true; QPainter painter; painter.begin(image); //if(m_data->degu != NULL && m_data->degu->instances.size() > 0) { //SpHullModel h = m_data->degu->instances.back()->hull; //SpHullModel hl = newHull; SpHullModel hl = modeloMain->second->deguShape; if(!hl.isNull()) { displayShowHull(painter, hl); displayShowAxis(painter, hl); displayShowNormals(painter, hl); //displayShowHead(painter, m_data->degu, h->off_x, h->off_y); } //displayShowTrajectory(painter, m_data->degu->trajectory); //} cv::Point2d head=modeloMain->second->headLocation; QPoint headP(head.x,head.y); painter.drawEllipse(headP, 20,20); painter.end(); return true; }
void LightMaps::paintEvent(QPaintEvent *event) { QPainter p; p.begin(this); m_normalMap->render(&p, event->rect()); p.setPen(Qt::black); #if defined(Q_OS_SYMBIAN) QFont font = p.font(); font.setPixelSize(13); p.setFont(font); #endif p.drawText(rect(), Qt::AlignBottom | Qt::TextWordWrap, "Map data CCBYSA 2009 OpenStreetMap.org contributors"); p.end(); if (zoomed) { int dim = qMin(width(), height()); int magnifierSize = qMin(MAX_MAGNIFIER, dim * 2 / 3); int radius = magnifierSize / 2; int ring = radius - 15; QSize box = QSize(magnifierSize, magnifierSize); // reupdate our mask if (maskPixmap.size() != box) { maskPixmap = QPixmap(box); maskPixmap.fill(Qt::transparent); QRadialGradient g; g.setCenter(radius, radius); g.setFocalPoint(radius, radius); g.setRadius(radius); g.setColorAt(1.0, QColor(255, 255, 255, 0)); g.setColorAt(0.5, QColor(128, 128, 128, 255)); QPainter mask(&maskPixmap); mask.setRenderHint(QPainter::Antialiasing); mask.setCompositionMode(QPainter::CompositionMode_Source); mask.setBrush(g); mask.setPen(Qt::NoPen); mask.drawRect(maskPixmap.rect()); mask.setBrush(QColor(Qt::transparent)); mask.drawEllipse(g.center(), ring, ring); mask.end(); } QPoint center = dragPos - QPoint(0, radius); center = center + QPoint(0, radius / 2); QPoint corner = center - QPoint(radius, radius); QPoint xy = center * 2 - QPoint(radius, radius); // only set the dimension to the magnified portion if (zoomPixmap.size() != box) { zoomPixmap = QPixmap(box); zoomPixmap.fill(Qt::lightGray); } if (true) { QPainter p(&zoomPixmap); p.translate(-xy); m_largeMap->render(&p, QRect(xy, box)); p.end(); } QPainterPath clipPath; clipPath.addEllipse(center, ring, ring); QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.setClipPath(clipPath); p.drawPixmap(corner, zoomPixmap); p.setClipping(false); p.drawPixmap(corner, maskPixmap); p.setPen(Qt::gray); p.drawPath(clipPath); } if (invert) { QPainter p(this); p.setCompositionMode(QPainter::CompositionMode_Difference); p.fillRect(event->rect(), Qt::white); p.end(); } }
void EstateDetails::paintEvent(QPaintEvent *) { if (m_recreateQuartz) { /* if (m_quartzBlocks) { delete m_quartzBlocks; m_quartzBlocks = 0; } if (m_estate->color().isValid()) { m_quartzBlocks = new KPixmap(); if (m_orientation == North || m_orientation == South) m_quartzBlocks->resize(25, m_titleHeight-2); else m_quartzBlocks->resize(25, m_titleWidth-2); drawQuartzBlocks(m_quartzBlocks, *m_quartzBlocks, m_estate->color().light(60), m_estate->color()); m_quartzBlocks = rotatePixmap(m_quartzBlocks); } */ m_recreateQuartz = false; b_recreate = true; } if (b_recreate) { delete m_pixmap; m_pixmap = new QPixmap(width(), height()); QColor greenHouse(0, 255, 0); QColor redHotel(255, 51, 51); QPainter painter; painter.begin(m_pixmap, this); painter.setPen(Qt::black); painter.setBrush(m_estate ? m_estate->bgColor() : Qt::white); painter.drawRect(rect()); /* // Paint icon only when it exists and fits if (icon!=0 && width() > icon->width() && height() > icon->height()) painter.drawPixmap( (width() - icon->width())/2, (height() - icon->height())/2, *icon); */ if (m_estate) { int titleHeight = 50; QColor titleColor = (m_estate->color().isValid() ? m_estate->color() : m_estate->bgColor().light(80)); KPixmap* quartzBuffer = new KPixmap; quartzBuffer->resize(25, (height()/4)-2); QPainter quartzPainter; quartzPainter.begin(quartzBuffer, this); painter.setBrush(titleColor); painter.drawRect(0, 0, width(), titleHeight); if (m_quartzBlocks) { quartzPainter.drawPixmap(0, 0, *m_quartzBlocks); painter.drawPixmap(1, 1, *quartzBuffer); } if (m_estate->houses() > 0) { int titleWidth = width() / 5; if (m_estate->houses() == 5) { // Hotel painter.setBrush(redHotel); painter.drawRect(2, 2, titleWidth-4, titleHeight-4); } else { // Houses painter.setBrush(greenHouse); int h = titleHeight-4, w = titleWidth-4; for ( unsigned int i=0 ; i < m_estate->houses() ; i++ ) painter.drawRect(2+(i*(w+2)), 2, w, h); } } quartzPainter.end(); delete quartzBuffer; // TODO: steal blur code from kicker/taskbar/taskcontainer.cpp // Estate name painter.setPen(Qt::white); int fontSize = KGlobalSettings::generalFont().pointSize(); if (fontSize == -1) fontSize = KGlobalSettings::generalFont().pixelSize(); painter.setFont(QFont(KGlobalSettings::generalFont().family(), fontSize * 2, QFont::Bold)); painter.drawText(KDialog::marginHint(), KDialog::marginHint(), width()-KDialog::marginHint(), titleHeight, Qt::AlignJustify, m_estate->name()); painter.setPen(Qt::black); int xText = 0; // Estate group if (m_estate->estateGroup()) { xText = titleHeight - fontSize - KDialog::marginHint(); painter.setFont(QFont(KGlobalSettings::generalFont().family(), fontSize, QFont::Bold)); painter.drawText(5, xText, width()-10, titleHeight, Qt::AlignRight, m_estate->estateGroup()->name().upper()); } xText = titleHeight + fontSize + 5; painter.setFont(QFont(KGlobalSettings::generalFont().family(), fontSize, QFont::Normal)); } b_recreate = false; } bitBlt(this, 0, 0, m_pixmap); }
/* This regenrate optimize pixmap. there is single squire image which is repeated n no. of times to genrate new pixmap this new pixmap is translated to move horizontaly or verticaly depending on orientation. */ void HbRepeatIconItem::resizeEvent ( QGraphicsSceneResizeEvent * event ) { Q_UNUSED(event); mParentRect = parentItem()->boundingRect(); HbFrameDrawer drawer; if(mOrientation == Qt::Horizontal){ drawer.setFrameGraphicsName("qtg_fr_progbar_h_mask"); drawer.setFrameType(HbFrameDrawer::ThreePiecesHorizontal); setIconHeight(mParentRect.size().toSize().height());//set height of the image drawer } else{ drawer.setFrameGraphicsName("qtg_fr_progbar_v_mask"); drawer.setFrameType(HbFrameDrawer::ThreePiecesVertical); setIconWidth(mParentRect.size().toSize().width());//set width of the image drawer } drawer.setFillWholeRect(true); QPixmap track(mParentRect.size().toSize()); track.fill(Qt::white); QPainter p; p.begin(&track); drawer.paint(&p, QRectF(QPointF(0,0),mParentRect.size() )); p.end(); setGeometry(QRectF(QPointF(0,0),mParentRect.size() ));//set geometry of QGI QImage i=track.toImage(); //i.invertPixels(); setMask(QPixmap::fromImage(i)); if(mRepeatPixmap){ delete mRepeatPixmap; mRepeatPixmap = 0; } qreal rectWidth = mParentRect.size().width(); //newSize.width(); qreal iconWidth = mIcon.width(); qreal rectHeight = mParentRect.size().height(); qreal iconHeight = mIcon.height(); if(mOrientation == Qt::Horizontal){ mRepeatPixmap = new QPixmap(int(rectWidth + iconWidth), (int)iconHeight); mRepeatPixmap->fill(Qt::white); QPainter p2; p2.begin(mRepeatPixmap); if(iconWidth > 0){ for(qreal i = 0 ; i < (rectWidth + iconWidth) ; i += iconWidth) { mIcon.paint(&p2, QRectF(i, 0, iconWidth, iconHeight), mMode); } } p2.end(); } else{ mRepeatPixmap = new QPixmap((int)iconWidth, int(rectHeight + iconHeight)); mRepeatPixmap->fill(Qt::white); QPainter p2; p2.begin(mRepeatPixmap); if( iconHeight > 0 ){ for(qreal i = 0 ; i < (rectHeight + iconHeight) ; i += iconHeight) { mIcon.paint(&p2, QRectF(0, i, iconWidth, iconHeight), mMode); } } p2.end(); } }
void PrintLayout::printTable() { struct dive *dive; int done = 0; // percents done int i, row = 0, progress, total = estimateTotalDives(); if (!total) return; // create and setup a table QTableView table; table.setAttribute(Qt::WA_DontShowOnScreen); table.setSelectionMode(QAbstractItemView::NoSelection); table.setFocusPolicy(Qt::NoFocus); table.horizontalHeader()->setVisible(false); table.verticalHeader()->setVisible(false); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) table.horizontalHeader()->setResizeMode(QHeaderView::Fixed); table.verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); #else table.horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); table.verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); #endif table.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // fit table to one page initially table.resize(pageW, pageH); // don't show border table.setStyleSheet( "QTableView { border: none }"); // create and fill a table model TablePrintModel model; addTablePrintHeadingRow(&model, row); // add one heading row row++; progress = 0; for_each_dive (i, dive) { if (!dive->selected && printOptions->print_selected) continue; addTablePrintDataRow(&model, row, dive); row++; progress++; emit signalProgress((progress * 10) / total); } done = 10; table.setModel(&model); // set model to table // resize columns to percentages from page width int accW = 0; int cols = model.columns; int tableW = table.width(); for (i = 0; i < model.columns; i++) { int pw = qCeil((qreal)(tablePrintColumnWidths.at(i) * table.width()) / 100.0); accW += pw; if (i == cols - 1 && accW > tableW) /* adjust last column */ pw -= accW - tableW; table.horizontalHeader()->resizeSection(i, pw); } // reset the model at this point model.callReset(); // a list of vertical offsets where pages begin and some helpers QList<unsigned int> pageIndexes; pageIndexes.append(0); /* the algorithm bellow processes the table rows in multiple passes, * compensating for loss of space due to moving rows on a new page instead * of truncating them. * there is a 'passes' array defining how much percents of the total * progress each will take. given, the first and last stage of this function * use 10% each, then the sum of passes[] here should be 80%. * two should be enough! */ const int passes[] = { 70, 10 }; int tableHeight = 0, lastAccIndex = 0, rowH, accH, headings, headingRowHeightD2, headingRowHeight; bool newHeading = false; for (unsigned int pass = 0; pass < sizeof(passes) / sizeof(passes[0]); pass++) { progress = headings = accH = 0; total = model.rows - lastAccIndex; for (i = lastAccIndex; i < model.rows; i++) { rowH = table.rowHeight(i); if (i == 0) { // first row is always a heading. it's height is constant. headingRowHeight = rowH; headingRowHeightD2 = rowH / 2; } if (rowH > pageH - headingRowHeight) // skip huge rows. we don't support row spanning on multiple pages. continue; accH += rowH; if (newHeading) { headings += rowH; newHeading = false; } if (accH > pageH) { lastAccIndex = i; pageIndexes.append(pageIndexes.last() + (accH - rowH)); addTablePrintHeadingRow(&model, i); newHeading = true; accH = 0; i--; } tableHeight += table.rowHeight(i); progress++; emit signalProgress(done + (progress * passes[pass]) / total); } done += passes[pass]; } done = 90; pageIndexes.append(pageIndexes.last() + accH + headings); table.resize(pageW, tableHeight); /* attach a painter and render pages by using pageIndexes * there is a weird QPicture dependency here; we need to offset a page * by headingRowHeightD2, which is half the heading height. the same doesn't * make sense if we are rendering the table widget directly to the printer-painter. */ QPainter painter(printer); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::SmoothPixmapTransform); total = pageIndexes.size() - 1; progress = 0; for (i = 0; i < total; i++) { if (i > 0) printer->newPage(); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) (void)headingRowHeightD2; QRegion region(0, pageIndexes.at(i) - 1, table.width(), pageIndexes.at(i + 1) - pageIndexes.at(i) + 1); table.render(&painter, QPoint(0, 0), region); #else QRegion region(0, pageIndexes.at(i) + headingRowHeightD2 - 1, table.width(), pageIndexes.at(i + 1) - (pageIndexes.at(i) + headingRowHeightD2) + 1); // vectorize the table first by using QPicture QPicture pic; QPainter picPainter; picPainter.begin(&pic); table.render(&picPainter, QPoint(0, 0), region); picPainter.end(); painter.drawPicture(QPoint(0, headingRowHeightD2), pic); #endif progress++; emit signalProgress(done + (progress * 10) / total); } }
bool QgsSvgMarkerSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, const QgsSymbolV2RenderContext* context, const QgsFeature* f, const QPointF& shift ) const { Q_UNUSED( layerName ); Q_UNUSED( shift ); //todo... QSvgRenderer r( mPath ); if ( !r.isValid() ) { return false; } QgsDxfPaintDevice pd( &e ); pd.setDrawingSize( QSizeF( r.defaultSize() ) ); //size double size = mSize; QgsExpression* sizeExpression = expression( "size" ); bool hasDataDefinedSize = context->renderHints() & QgsSymbolV2::DataDefinedSizeScale || sizeExpression; if ( sizeExpression ) { size = sizeExpression->evaluate( *f ).toDouble(); } if ( mSizeUnit == QgsSymbolV2::MM ) { size *= mmMapUnitScaleFactor; } if ( hasDataDefinedSize ) { switch ( mScaleMethod ) { case QgsSymbolV2::ScaleArea: size = sqrt( size ); break; case QgsSymbolV2::ScaleDiameter: break; } } double halfSize = size / 2.0; //offset, angle QPointF offset = mOffset; QgsExpression* offsetExpression = expression( "offset" ); if ( offsetExpression ) { QString offsetString = offsetExpression->evaluate( *f ).toString(); offset = QgsSymbolLayerV2Utils::decodePoint( offsetString ); } double offsetX = offset.x(); double offsetY = offset.y(); if ( mSizeUnit == QgsSymbolV2::MM ) { offsetX *= mmMapUnitScaleFactor; offsetY *= mmMapUnitScaleFactor; } QPointF outputOffset( offsetX, offsetY ); double angle = mAngle; QgsExpression* angleExpression = expression( "angle" ); if ( angleExpression ) { angle = angleExpression->evaluate( *f ).toDouble(); } //angle = -angle; //rotation in Qt is counterclockwise if ( angle ) outputOffset = _rotatedOffset( outputOffset, angle ); QPainter p; p.begin( &pd ); if ( !qgsDoubleNear( angle, 0.0 ) ) { p.translate( r.defaultSize().width() / 2.0, r.defaultSize().height() / 2.0 ); p.rotate( angle ); p.translate( -r.defaultSize().width() / 2.0, -r.defaultSize().height() / 2.0 ); } pd.setShift( shift ); pd.setOutputSize( QRectF( -halfSize, -halfSize, size, size ) ); pd.setLayer( layerName ); r.render( &p ); p.end(); return true; }
Altimeter::Altimeter(QWidget *parent) : QGraphicsView(parent), feets(0) { QPolygon polygon; // helper this->setGeometry(0,0, WIDGETSIZE, WIDGETSIZE); // Style Setting backgroundBrush = QBrush(Qt::black);//QBrush(QColor(0x53, 0x54, 0x48)); circlePen = QPen(Qt::white); circlePen.setWidth(CIRCLEPENWIDTH); graduationPen = QPen(Qt::white); graduationPen.setWidth(2); graduationFont = QFont("lucida"); graduationFont.setPointSize(12); graduationFont.setBold(true); handPenFront = QPen(Qt::black); handPenFront.setWidth(2); handPenBack = QPen(Qt::white); handPenBack.setWidth(2); handBrushBack = QBrush(Qt::black); handBrushFront = QBrush(Qt::white); // BACKGROUND PIXMAP backgroundPixmap = QPixmap(WIDGETSIZE,WIDGETSIZE); QPainter painter; painter.begin(&(this->backgroundPixmap)); painter.setRenderHint(QPainter::Antialiasing); // Background painter.fillRect(QRect(0,0,WIDGETSIZE,WIDGETSIZE), backgroundBrush); // Circle painter.translate(WIDGETSIZE/2, WIDGETSIZE/2); painter.setBrush(Qt::NoBrush); painter.setPen(circlePen); painter.drawEllipse(QPoint(0,0), (WIDGETSIZE/2-CIRCLEPENWIDTH), (WIDGETSIZE/2-CIRCLEPENWIDTH) ); // Graduation painter.save(); painter.setFont(graduationFont); for(int i=0 ; i<10 ; ++i) { graduationPen.setWidth(2); painter.setPen(graduationPen); painter.drawLine(QPoint(0, -(WIDGETSIZE/2-CIRCLEPENWIDTH)+5), QPoint(0, -(WIDGETSIZE/2-CIRCLEPENWIDTH)+13)); graduationPen.setWidth(1); painter.setPen(graduationPen); painter.drawText( QPoint(-5, -(WIDGETSIZE/2-CIRCLEPENWIDTH)+28), QString::number(i)); for(int j=1 ; j<5 ; ++j) { painter.rotate(7.2); painter.drawLine(QPoint(0, -(WIDGETSIZE/2-CIRCLEPENWIDTH)+5), QPoint(0, -(WIDGETSIZE/2-CIRCLEPENWIDTH)+10)); } painter.rotate(7.2); } painter.restore(); painter.end(); // HAND, FEETS feetsHand = QPixmap(HANDWIDTH, HANDHEIGHT); painter.begin(&(this->feetsHand)); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(feetsHand.rect(), backgroundBrush); // Hand front painter.setBrush(handBrushFront); painter.setPen(handPenFront); painter.drawRect(QRect(HANDCENTERX-2, CIRCLEPENWIDTH+5, 4, 16)); painter.drawRect(QRect( QPoint(HANDCENTERX-3, CIRCLEPENWIDTH+5+15), QPoint(HANDCENTERX+3, HANDCENTERY)) ); // Hand back painter.setBrush(handBrushBack); painter.setPen(handPenBack); painter.drawRect(HANDCENTERX-3, HANDCENTERY, 6, 25); painter.drawEllipse(QPoint(HANDCENTERX, HANDCENTERY+25), 6, 6); painter.end(); // Mask feetsHand.setMask(feetsHand.createMaskFromColor( backgroundBrush.color(), Qt::MaskInColor) ); // HAND, TENTH of FEETS tenthHand = QPixmap(HANDWIDTH, HANDHEIGHT); painter.begin(&(this->tenthHand)); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(tenthHand.rect(), backgroundBrush); // Hand front painter.setBrush(handBrushFront); painter.setPen(handPenFront); polygon.append(HANDCENTER); polygon.append(QPoint(HANDCENTERX-10, HANDCENTERY-25)); polygon.append(QPoint(HANDCENTERX, HANDCENTERY-75)); polygon.append(QPoint(HANDCENTERX+10, HANDCENTERY-25)); painter.drawPolygon(polygon); // Hand back painter.setBrush(handBrushBack); painter.setPen(handPenBack); polygon.clear(); polygon.append(HANDCENTER); polygon.append(QPoint(HANDCENTERX-10, HANDCENTERY+25)); polygon.append(QPoint(HANDCENTERX+10, HANDCENTERY+25)); painter.drawPolygon(polygon); painter.end(); // Mask tenthHand.setMask(tenthHand.createMaskFromColor( backgroundBrush.color(), Qt::MaskInColor) ); // HAND, HUNDREDS of FEETS hundredsHand = QPixmap(HANDWIDTH, HANDHEIGHT); painter.begin(&(this->hundredsHand)); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(hundredsHand.rect(), backgroundBrush); // Hand front painter.setBrush(handBrushFront); painter.setPen(handPenFront); painter.drawRect(QRect( HANDCENTERX-2, CIRCLEPENWIDTH+5, 4, HANDCENTERY-CIRCLEPENWIDTH-5) ); polygon.clear(); polygon.append(QPoint(HANDCENTERX-10, CIRCLEPENWIDTH+5)); polygon.append(QPoint(HANDCENTERX+10, CIRCLEPENWIDTH+5)); polygon.append(QPoint(HANDCENTERX, CIRCLEPENWIDTH+5+15)); painter.drawPolygon(polygon); // Hand back painter.setBrush(handBrushBack); painter.setPen(handPenBack); painter.end(); // Mask hundredsHand.setMask(hundredsHand.createMaskFromColor( backgroundBrush.color(), Qt::MaskInColor) ); }
void OrbitsWidget::paintEvent(QPaintEvent*) { QPainter DC; DC.begin(this); DC.setRenderHint(QPainter::Antialiasing, true); int min_size = qMin(width(), height()); int min_delta = min_size / 10; const int num = numOfElectrons.count(); if (num == 0) { DC.drawText(QPoint(width() / 3, height() / 3), i18n("Unknown Electron Distribution")); return; // no orbits, do nothing } //make sure the biggest orbit fits in the widget //diameter int d = min_size - 2 * min_delta; //the radius of the current orbit int r = d / 2; //the radius of an 'electron' int r_electron = r / 20; //difference to the previous circle int ddx = r / num; QList<int>::Iterator it = numOfElectrons.end(); --it; for (int i = 0; i < num; ++i) { int mx = min_delta + ddx * i; //the x-coordinate for the current circle int my = min_delta + ddx * i; //the y-coordinate for the current circle DC.setBrush(Qt::NoBrush); DC.setPen(Qt::black); //draw the big ellipses in concentric circles DC.drawEllipse(mx, my, d, d); DC.setPen(Qt::NoPen); for (int e = 0; e < *it; ++e) { int x = (int)translateToDX(d / 2.0, (double)e, *it); int y = (int)translateToDY(d / 2.0, (double)e, *it); //Creating a gradient for the current electron. QRadialGradient grad(QPointF(x + mx + d / 2 - r_electron / 2, y + my + d / 2 - r_electron / 2), r_electron); grad.setColorAt(0, Qt::white); grad.setColorAt(0.2, Qt::yellow); grad.setColorAt(1, QColor(Qt::yellow).darker()); DC.setBrush(QBrush(grad)); DC.drawEllipse(x + mx + d / 2 - r_electron, y + my + d / 2 - r_electron, 2 * r_electron, 2 * r_electron); } --it; d -= 2 * ddx; } }
void KniftyClient::update_captionBuffer() { if (!KniftyHandler::initialized()) return; const uint maxCaptionLength = 300; // truncate captions longer than this! QString captionText(caption() ); if (captionText.length() > maxCaptionLength) { captionText.truncate(maxCaptionLength); captionText.append(" [...]"); } QFontMetrics fm(s_titleFont); int captionWidth = fm.width(captionText); QPixmap textPixmap; QPainter painter; if(KniftyHandler::titleShadow()) { // prepare the shadow textPixmap = QPixmap(captionWidth+2*2, s_titleHeight ); // 2*2 px shadow space textPixmap.fill(QColor(0,0,0)); textPixmap.setMask( textPixmap.createHeuristicMask(TRUE) ); painter.begin(&textPixmap); painter.setFont(s_titleFont); painter.setPen(white); painter.drawText(textPixmap.rect(), AlignCenter, captionText ); painter.end(); } QImage shadow; ShadowEngine se; // active aCaptionBuffer->resize(captionWidth+4, s_titleHeight ); // 4 px shadow painter.begin(aCaptionBuffer); painter.drawTiledPixmap(aCaptionBuffer->rect(), *aTitleBarTile); if(KniftyHandler::titleShadow()) { shadow = se.makeShadow(textPixmap, QColor(0, 0, 0)); painter.drawImage(1, 1, shadow); } painter.setFont(s_titleFont); painter.setPen(options()->color(KDecoration::ColorFont, true)); painter.drawText(aCaptionBuffer->rect(), AlignCenter, captionText ); painter.end(); // inactive iCaptionBuffer->resize(captionWidth+4, s_titleHeight ); painter.begin(iCaptionBuffer); painter.drawTiledPixmap(iCaptionBuffer->rect(), *iTitleBarTile); if(KniftyHandler::titleShadow()) { painter.drawImage(1, 1, shadow); } painter.setFont(s_titleFont); painter.setPen(options()->color(KDecoration::ColorFont, false)); painter.drawText(iCaptionBuffer->rect(), AlignCenter, captionText ); painter.end(); captionBufferDirty = false; }
// creates a polygon from a given vector RegularData1D * data void RegularData2DWidget::createPlot() { // no data => no polygon if (data_ == 0 || data_->size() == 0) { return; } // set up the ColorMap... TODO: This should be done by a dialog or something similar ColorRGBA colorList[3]; ColorMap color_table_; colorList[0] = ColorRGBA(1.,0.,0.,1.); colorList[1] = ColorRGBA(0.,1.,0.,1.); colorList[2] = ColorRGBA(0.,0.,1.,1.); color_table_.setBaseColors(colorList, 3); color_table_.setNumberOfColors(100); // determine the minimal and maximal values in data_ float min = (*data_)[0]; float max = (*data_)[0]; for (Position i=1; i < (*data_).size(); i++) { if ((*data_)[i] < min) min = (*data_)[i]; else if ((*data_)[i] > max) max = (*data_)[i]; } color_table_.setRange(min, max); color_table_.createMap(); //maximal number of Lines and Columns Size max_x = (*data_).getSize().x; Size max_y = (*data_).getSize().y; // Draw the points QPixmap pixmap; pixmap.resize(max_x, max_y); pixmap.fill(); // delete the old picture QPainter paint; paint.begin(&pixmap); // set the Painter try { QColor pCol; for (Position y=0; y< max_y; y++) { for (Position x=0; x< max_x; x++) { ColorRGBA mapcolor = color_table_.map(data_->getData(x + y * max_x)); pCol = QColor(mapcolor.getRed(), mapcolor.getGreen(), mapcolor.getBlue()); paint.setPen(pCol); paint.drawPoint(x, y); } } } catch(...) { setStatusbarText("Error: Point in dataset out of grid!"); Log.error() << "Error: Point in dataset out of grid!" << std::endl; return; } paint.end(); //put the pixmapItem into objects PixmapItem* pixItem = new PixmapItem(&canvas_, pixmap); pixItem->show(); objects_.push_back(dynamic_cast<Q3CanvasItem*> (pixItem)); // resize the canvas to fit the data canvas_.resize(max_x, max_y); }
void SXBSchView::print(QPrinter* pPrinter) { m_pDoc->resetSelect(); updateViewBuffer(true); QPainter paint; if(paint.begin(pPrinter ) ) { int dpi; #ifdef Q_WS_MACX int dpix,dpiy;; dpix = pPrinter->logicalDpiX(); dpiy = pPrinter->logicalDpiY(); dpi=((dpix < dpiy) ? dpix : dpiy); #else dpi = pPrinter->resolution(); #endif paint.setRenderHint(QPainter::Antialiasing, true); // QRect rcPaper = pPrinter->paperRect(); // printf("paperRect %d,%d,%d,%d\n",rcPaper.left(),rcPaper.top(),rcPaper.width(),rcPaper.height()); QRect rcVp = paint.viewport(); QRect rcPg = pPrinter->pageRect(); // printf("pageRect %d,%d,%d,%d\n",rcPg.left(),rcPg.top(),rcPg.width(),rcPg.height()); // int orientation = pPrinter->orientation(); // printf("orientation %d\n",orientation); int vpWidth, vpHeight; int pgLeft, pgTop, pgWidth, pgHeight; vpWidth =rcVp.width(); vpHeight = rcVp.height(); pgLeft =rcPg.left(); pgTop =rcPg.top(); pgWidth =rcPg.width(); pgHeight = rcPg.height(); //印刷時に印刷の向きを変えてもpageRect()の返す値が変わらないQtのバグ(?)の対策 if( (vpWidth > vpHeight && pgWidth < pgHeight) || (vpWidth < vpHeight && pgWidth > pgHeight) ) { int swapn; swapn = pgLeft; pgLeft = pgTop; pgTop = swapn; swapn = pgWidth; pgWidth = pgHeight; pgHeight = swapn; } QSettings *settings = g_cfg.getSettings(); int leftMargin = 15; int topMargin = 15; int rightMargin = 15; int bottomMargin = 15; settings->beginGroup("PrintOption"); bool color = settings->value("Color",true).toBool(); settings->endGroup(); settings->beginGroup("PrintMargin"); topMargin = settings->value("Top",15).toInt(); bottomMargin = settings->value("Bottom",15).toInt(); leftMargin = settings->value("Left",15).toInt(); rightMargin = settings->value("Right",15).toInt(); settings->endGroup(); if (topMargin < 0) topMargin = 0; else if (topMargin > 50) topMargin = 50; if (bottomMargin < 0) bottomMargin = 0; else if (bottomMargin > 50) bottomMargin = 50; if (leftMargin < 0) leftMargin = 0; else if (leftMargin > 50) leftMargin = 50; if (rightMargin < 0) rightMargin = 0; else if (rightMargin > 50) rightMargin = 50; topMargin = dpi * 10 * topMargin / 254; bottomMargin = dpi * 10 * bottomMargin / 254; leftMargin = dpi * 10 * leftMargin / 254; rightMargin = dpi * 10 * rightMargin / 254; // printf("SXBSchView::print() dpi:%d\n",dpi); paint.save(); paint.setViewTransformEnabled (true); paint.resetMatrix(); SSize size = m_pDoc->SheetSize(); int w = size.w(); int h = size.h(); int dw = w*10; int dh = h*10; // p->setWindow( 0,0, dw, dh ); // QRect rc = paint.viewport(); int rightWidth = vpWidth-(pgLeft+pgWidth); if(rightWidth < 0) rightWidth = 0; int bottomWidth = vpHeight-(pgTop+pgHeight); if(bottomWidth < 0) bottomWidth = 0; leftMargin -= pgLeft; if(leftMargin < 0)leftMargin = 0; topMargin -= pgTop; if(topMargin < 0) topMargin = 0; rightMargin -= rightWidth; if(rightMargin < 0) rightMargin = 0; bottomMargin -= bottomWidth; if(bottomMargin < 0) bottomMargin = 0; int vw = pgWidth-(leftMargin+rightMargin); int vh = pgHeight-(topMargin+bottomMargin); double sheetRatio=(double)w / (double)h; double viewRatio=(double)vw / (double)vh; int newW; int newH; if(sheetRatio > viewRatio) { newW = vw; newH = (int)(vw / sheetRatio); } else { newH = vh; newW = (int)(vh * sheetRatio); } // printf("newW,H=%d,%d\n",newW,newH); // p->setViewport( rc.left() + (vw-newW)/2, // rc.top() + (vh-newH)/2, // newW, newH ); // QRect rcvp = p->viewport(); // printf("x,y,w,h %d,%d,%d,%d\n",rcvp.x(),rcvp.y(),rcvp.width(),rcvp.height()); paint.setViewport( leftMargin+ (vw-newW)/2, topMargin + (vh-newH)/2, newW, newH ); paint.setWindow( 0,0, dw, dh ); // rcvp = p->viewport(); // printf("x,y,w,h %d,%d,%d,%d\n",rcvp.x(),rcvp.y(),rcvp.width(),rcvp.height()); QRect rcClip = QRect(0,0,dw,dh); SRect srcClip =SRect(0,0,w,h); paint.setBackground(Qt::white); paint.eraseRect(0,0,dw,dh); g_drawFrame(&paint,size,rcClip,Qt::black,1,10); drawMainXBSchObj(&paint,(color ? DRAW_ON : DRAW_MONO)|DRAW_FOR_PRINT,&srcClip,false,1,10); paint.restore(); paint.end(); } }
BalloonMsg::BalloonMsg(void *param, const QString &_text, QStringList &btn, QWidget *parent, const QRect *rcParent, bool bModal, bool bAutoHide, unsigned bwidth, const QString &box_msg, bool *bChecked) : QDialog(parent, "ballon", bModal, (bAutoHide ? WType_Popup : WType_TopLevel | WStyle_StaysOnTop) | WStyle_Customize | WStyle_NoBorderEx | WStyle_Tool | WDestructiveClose | WX11BypassWM) { m_param = param; m_parent = parent; m_width = bwidth; m_bAutoHide = bAutoHide; m_bYes = false; m_bChecked = bChecked; bool bTailDown = true; setPalette(QToolTip::palette()); text = _text; QFrame *frm = new QFrame(this); frm->setPalette(palette()); QVBoxLayout *vlay = new QVBoxLayout(frm); vlay->setMargin(0); m_check = NULL; if (!box_msg.isEmpty()){ m_check = new QCheckBox(box_msg, frm); vlay->addWidget(m_check); if (m_bChecked) m_check->setChecked(*m_bChecked); } QHBoxLayout *lay = new QHBoxLayout(vlay); lay->setSpacing(5); lay->addStretch(); unsigned id = 0; bool bFirst = true; for (QStringList::Iterator it = btn.begin(); it != btn.end(); ++it, id++){ BalloonButton *b = new BalloonButton(*it, frm, id); connect(b, SIGNAL(action(int)), this, SLOT(action(int))); lay->addWidget(b); if (bFirst){ b->setDefault(true); bFirst = false; } } setButtonsPict(this); lay->addStretch(); int wndWidth = frm->minimumSizeHint().width(); int hButton = frm->minimumSizeHint().height(); int txtWidth = bwidth; QRect rc; if (rcParent){ rc = *rcParent; }else{ QPoint p = parent->mapToGlobal(parent->rect().topLeft()); rc = QRect(p.x(), p.y(), parent->width(), parent->height()); } if (rc.width() > txtWidth) txtWidth = rc.width(); QSimpleRichText richText(_text, font(), "", QStyleSheet::defaultSheet(), QMimeSourceFactory::defaultFactory(), -1, Qt::blue, false); richText.setWidth(wndWidth); richText.adjustSize(); QSize s(richText.widthUsed(), richText.height()); QSize sMin = frm->minimumSizeHint(); if (s.width() < sMin.width()) s.setWidth(sMin.width()); int BALLOON_SHADOW = BALLOON_SHADOW_DEF; #ifdef WIN32 /* FIXME */ /* if ((GetClassLong(winId(), GCL_STYLE) & CS_DROPSHADOW) && style().inherits("QWindowsXPStyle")) BALLOON_SHADOW = 0; */ #endif resize(s.width() + BALLOON_R * 2 + BALLOON_SHADOW, s.height() + BALLOON_R * 2 + BALLOON_TAIL + BALLOON_SHADOW + hButton + BALLOON_MARGIN); mask = QBitmap(width(), height()); int w = width() - BALLOON_SHADOW; int tailX = w / 2; int posX = rc.left() + rc.width() / 2 + BALLOON_TAIL_WIDTH - tailX; if (posX <= 0) posX = 1; QRect rcScreen = screenGeometry(); if (posX + width() >= rcScreen.width()) posX = rcScreen.width() - 1 - width(); int tx = posX + tailX - BALLOON_TAIL_WIDTH; if (tx < rc.left()) tx = rc.left(); if (tx > rc.left() + rc.width()) tx = rc.left() + rc.width(); tailX = tx + BALLOON_TAIL_WIDTH - posX; if (tailX < BALLOON_R) tailX = BALLOON_R; if (tailX > width() - BALLOON_R - BALLOON_TAIL_WIDTH) tailX = width() - BALLOON_R - BALLOON_TAIL_WIDTH; if (rc.top() <= height() + 2){ bTailDown = false; move(posX, rc.top() + rc.height() + 1); }else{ move(posX, rc.top() - height() - 1); } int pos = 0; int h = height() - BALLOON_SHADOW - BALLOON_TAIL; if (!bTailDown) pos += BALLOON_TAIL; textRect.setRect(BALLOON_R, pos + BALLOON_R, w - BALLOON_R * 2, h); frm->resize(s.width(), hButton); frm->move(BALLOON_R, pos + h - BALLOON_R - hButton); QPainter p; p.begin(&mask); #ifdef WIN32 QColor bg(255, 255, 255); QColor fg(0, 0, 0); #else QColor bg(0, 0, 0); QColor fg(255, 255, 255); #endif p.fillRect(0, 0, width(), height(), bg); p.fillRect(0, pos + BALLOON_R, w, h - BALLOON_R * 2, fg); p.fillRect(BALLOON_R, pos, w - BALLOON_R * 2, h, fg); p.fillRect(BALLOON_SHADOW, pos + BALLOON_R + BALLOON_SHADOW, w, h - BALLOON_R * 2, fg); p.fillRect(BALLOON_R + BALLOON_SHADOW, pos + BALLOON_SHADOW, w - BALLOON_R * 2, h, fg); p.setBrush(fg); p.drawEllipse(0, pos, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(w - BALLOON_R * 2, pos, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(w - BALLOON_R * 2, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(0, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(BALLOON_SHADOW, pos + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(w - BALLOON_R * 2 + BALLOON_SHADOW, pos + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(w - BALLOON_R * 2 + BALLOON_SHADOW, pos + h - BALLOON_R * 2 + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(BALLOON_SHADOW, pos + h - BALLOON_R * 2 + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2); QPointArray arr(3); arr.setPoint(0, tailX, bTailDown ? h : pos); arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH, bTailDown ? h : pos); arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH, bTailDown ? height() - BALLOON_SHADOW : 0); p.drawPolygon(arr); arr.setPoint(0, tailX + BALLOON_SHADOW, (bTailDown ? h : pos) + BALLOON_SHADOW); arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH + BALLOON_SHADOW, (bTailDown ? h : pos) + BALLOON_SHADOW); arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH + BALLOON_SHADOW, bTailDown ? height() : BALLOON_SHADOW); p.drawPolygon(arr); p.end(); setMask(mask); qApp->syncX(); QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), x(), y(), width(), height()); intensity(pict, -0.50f); p.begin(&pict); p.setBrush(colorGroup().background()); p.drawEllipse(0, pos, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(w - BALLOON_R * 2, pos, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(w - BALLOON_R * 2, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2); p.drawEllipse(0, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2); arr.setPoint(0, tailX, bTailDown ? h - 1 : pos + 1); arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH, bTailDown ? h - 1 : pos + 1); arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH, bTailDown ? height() - BALLOON_SHADOW : 0); p.drawPolygon(arr); p.fillRect(0, pos + BALLOON_R, w, h - BALLOON_R * 2, colorGroup().background()); p.fillRect(BALLOON_R, pos, w - BALLOON_R * 2, h, colorGroup().background()); p.drawLine(0, pos + BALLOON_R, 0, pos + h - BALLOON_R); p.drawLine(w - 1, pos + BALLOON_R, w - 1, pos + h - BALLOON_R); if (bTailDown){ p.drawLine(BALLOON_R, 0, w - BALLOON_R, 0); p.drawLine(BALLOON_R, h - 1, tailX, h - 1); p.drawLine(tailX + BALLOON_TAIL_WIDTH, h - 1, w - BALLOON_R, h - 1); }else{ p.drawLine(BALLOON_R, pos + h - 1, w - BALLOON_R, pos + h - 1); p.drawLine(BALLOON_R, pos, tailX, pos); p.drawLine(tailX + BALLOON_TAIL_WIDTH, pos, w - BALLOON_R, pos); } p.end(); setBackgroundPixmap(pict); setAutoMask(true); if (!bAutoHide) setFocusPolicy(NoFocus); QWidget *top = NULL; if (parent) top = parent->topLevelWidget(); if (top){ raiseWindow(top); top->installEventFilter(this); } }
//________________________________________________ void TransitionWidget::paintEvent( QPaintEvent* event ) { // fully transparent case if( opacity() >= 1.0 && endPixmap().isNull() ) return; if( !_paintEnabled ) return; // get rect QRect rect = event->rect(); if( !rect.isValid() ) rect = this->rect(); // local pixmap const bool paintOnWidget( testFlag( PaintOnWidget ) && !testFlag( Transparent ) ); if( !paintOnWidget ) { if( _currentPixmap.isNull() || _currentPixmap.size() != size() ) { _currentPixmap = QPixmap( size() ); } } // fill _currentPixmap.fill( Qt::transparent ); // copy local pixmap to current { QPainter p; // draw end pixmap first, provided that opacity is small enough if( opacity() >= 0.004 && !_endPixmap.isNull() ) { // faded endPixmap if parent target is transparent and opacity is if( opacity() <= 0.996 && testFlag( Transparent ) ) { fade( _endPixmap, _currentPixmap, opacity(), rect ); p.begin( &_currentPixmap ); p.setClipRect( event->rect() ); } else { if( paintOnWidget ) p.begin( this ); else p.begin( &_currentPixmap ); p.setClipRect( event->rect() ); p.drawPixmap( QPoint(), _endPixmap ); } } else { if( paintOnWidget ) p.begin( this ); else p.begin( &_currentPixmap ); p.setClipRect( event->rect() ); } // draw fading start pixmap if( opacity() <= 0.996 && !_startPixmap.isNull() ) { if( opacity() >= 0.004 ) { fade( _startPixmap, _localStartPixmap, 1.0-opacity(), rect ); p.drawPixmap( QPoint(), _localStartPixmap ); } else p.drawPixmap( QPoint(), _startPixmap ); } p.end(); } // copy current pixmap on widget if( !paintOnWidget ) { QPainter p( this ); p.setClipRect( event->rect() ); p.drawPixmap( QPoint(0,0), _currentPixmap ); p.end(); } }
void SkyMapQDraw::paintEvent( QPaintEvent *event ) { Q_UNUSED(event); // This is machinery to prevent multiple concurrent paint events / recursive paint events if( m_DrawLock ) { kDebug() << "I just prevented a recursive / concurrent draw!"; return; } setDrawLock( true ); calculateFPS(); //If computeSkymap is false, then we just refresh the window using the stored sky pixmap //and draw the "overlays" on top. This lets us update the overlay information rapidly //without needing to recompute the entire skymap. //use update() to trigger this "short" paint event; to force a full "recompute" //of the skymap, use forceUpdate(). if (!m_SkyMap->computeSkymap) { QPainter p; p.begin( this ); p.drawLine(0,0,1,1); // Dummy operation to circumvent bug. TODO: Add details p.drawPixmap( 0, 0, *m_SkyPixmap ); drawOverlays(p); p.end(); setDrawLock( false ); return ; // exit because the pixmap is repainted and that's all what we want } // FIXME: used to to notify infobox about possible change of object coordinates // Not elegant at all. Should find better option m_SkyMap->showFocusCoords(); m_SkyMap->setupProjector(); SkyQPainter psky(this, m_SkyPixmap); //FIXME: we may want to move this into the components. psky.begin(); //Draw all sky elements psky.drawSkyBackground(); m_KStarsData->skyComposite()->draw( &psky ); //Finish up psky.end(); QPainter psky2; psky2.begin( this ); psky2.drawLine(0,0,1,1); // Dummy op. psky2.drawPixmap( 0, 0, *m_SkyPixmap ); drawOverlays(psky2); psky2.end(); if(m_SkyMap->m_previewLegend) { m_SkyMap->m_legend.paintLegend(m_SkyPixmap); } m_SkyMap->computeSkymap = false; // use forceUpdate() to compute new skymap else old pixmap will be shown setDrawLock( false ); }
/** * @brief Axis::draw *rysuje oś * @return narysowaną właśnie oś */ QPixmap Axis::draw() { QFontMetrics fm(this->getFont()); const int tickCount = (this->max-this->min)/this->tick; const QString unit = this->showUnit?" "+this->unit:""; int textWidth = fm.width(QString::number(this->max)+unit); int textHeight = fm.height(); QPixmap temp; float space; //najdluzszy tekst for(int i=0; i<=tickCount; i++) { if(fm.width(QString::number(this->min+tick*i)+unit) > textWidth) textWidth = fm.width(QString::number(this->min+tick*i)+unit); } if(position==left || position==right) { //this->setGeometry(Geometry(0,0,textWidth+6+this->tickSize, this->geometry.getHeight())); int dodatek=0; if(this->label.getGeometry().getWidth()>0) dodatek = this->label.getGeometry().getWidth()+2; temp = QPixmap(textWidth+6+this->tickSize+dodatek, this->geometry.getHeight()); space = (temp.height()-20)/(max-min)*tick; if(position == left) textWidth += dodatek; } else { //this->setGeometry(Geometry(0, 0, this->geometry.getWidth(), textHeight+6+tickSize)); temp = QPixmap(this->geometry.getWidth(), textHeight+6+this->tickSize); space = (temp.width())/(max-min)*tick; } QPainter p; p.begin(&temp); p.fillRect(0, 0, temp.width(), temp.height(), Qt::white); p.setFont(this->getFont()); if(position==left) { if(this->label.getGeometry().getWidth() > 0) { //textWidth += this->label.getGeometry().getWidth()+2; p.drawPixmap(0, (temp.height()-this->label.getGeometry().getHeight())/2, this->label.draw()); } if(tickDirection==inside) p.drawLine(textWidth+5, 10, textWidth+5, temp.height()-10); else if(tickDirection == middle) p.drawLine(textWidth+5+tickSize/2, 10, textWidth+5+tickSize/2, temp.height()-10); else p.drawLine(textWidth+5+tickSize, 10, textWidth+5+tickSize, temp.height()-10); for(int i=tickCount; i>=0; i--) { p.drawLine(textWidth+5, temp.height()-10-i*space, textWidth+5+tickSize, temp.height()-10-i*space); p.drawText(0, temp.height()-10-i*space-textHeight/2, textWidth, textHeight, Qt::AlignRight, QString::number(min+tick*i)+unit); } p.drawLine(textWidth+5, 10, textWidth+5+tickSize, 10); } else if(position == right) { if(tickDirection==inside) p.drawLine(1+tickSize, 10, 1+tickSize, temp.height()-10); else if(tickDirection == middle) p.drawLine(1+tickSize/2, 10, 1+tickSize/2, temp.height()-10); else p.drawLine(1, 10, 1, temp.height()-10); for(int i=tickCount; i>=0; i--) { p.drawLine(1, temp.height()-10-i*space, 1+tickSize, temp.height()-10-i*space); p.drawText(6+tickSize, temp.height()-10-i*space-textHeight/2, textWidth, textHeight, Qt::AlignLeft, QString::number(min+tick*i)+unit); } p.drawLine(1, 10, 1+tickSize, 10); if(this->label.getGeometry().getWidth() > 0) { //textWidth += this->label.getGeometry().getWidth()+2; p.drawPixmap(6+tickSize+textWidth+2, (temp.height()-this->label.getGeometry().getHeight())/2, this->label.draw()); } } else if(position == bottom) { if(tickDirection==outside) p.drawLine(0, 1, temp.width(), 1); else if(tickDirection == middle) p.drawLine(0, 1+tickSize/2, temp.width(), 1+tickSize/2); else p.drawLine(0, 1+tickSize, temp.width(), 1+tickSize); for(int i=tickCount; i>=0; i--) { p.drawLine(i*space, 1, i*space, 1+tickSize); //p.drawText(6+tickSize, temp.height()-10-i*space+textHeight/2, QString::number(min+tick*i)+unit); } p.drawLine(temp.width()-1, 1, temp.width()-1, 1+tickSize); } else //top { if(tickDirection==outside) p.drawLine(10, 5+tickSize+textHeight, temp.width()-10, 5+tickSize+textHeight); else if(tickDirection == middle) p.drawLine(10, 5+tickSize/2+textHeight, temp.width()-10, 5+tickSize/2+textHeight); else p.drawLine(10, 5+textHeight, temp.width()-10, 5+textHeight); for(int i=tickCount; i>=0; i--) { p.drawLine(10+i*space, 6+textHeight, 10+i*space, 6+tickSize+textHeight); //p.drawText(6+tickSize, temp.height()-10-i*space+textHeight/2, QString::number(min+tick*i)+unit); } p.drawLine(temp.width()-10, 6+textHeight, temp.width()-10, 6+tickSize+textHeight); } p.end(); this->geometry.setWidth(temp.width()); this->geometry.setHeight(temp.height()); return temp; }
void PrintLayout::printProfileDives(int divesPerRow, int divesPerColumn) { int i, row = 0, col = 0, printed = 0, total = estimateTotalDives(); int animationOriginal = prefs.animation_speed; struct dive *dive; if (!total) return; // disable animations on the profile: prefs.animation_speed = 0; // setup a painter QPainter painter; painter.begin(printer); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::SmoothPixmapTransform); // setup the profile widget QPointer<ProfileWidget2> profile = MainWindow::instance()->graphics(); const int profileFrameStyle = profile->frameStyle(); profile->setFrameStyle(QFrame::NoFrame); profile->setPrintMode(true, !printOptions->color_selected); profile->setFontPrintScale(divesPerRow * divesPerColumn > 3 ? 0.6 : 1.0); QSize originalSize = profile->size(); // swap rows/col for landscape if (printer->orientation() == QPrinter::Landscape) { int swap = divesPerColumn; divesPerColumn = divesPerRow; divesPerRow = swap; } // padding in pixels between two dives. no padding if only one dive per page. const int padDef = 20; const int padW = (divesPerColumn < 2) ? 0 : padDef; const int padH = (divesPerRow < 2) ? 0 : padDef; // estimate dimensions for a single dive const int scaledW = ESTIMATE_DIVE_DIM(pageW, divesPerColumn, padW); const int scaledH = ESTIMATE_DIVE_DIM(pageH, divesPerRow, padH); // padding in pixels between profile and table const int padPT = 5; // create a model and table ProfilePrintModel model; model.setFontsize(7); // if this is changed we also need to change 'const int sr' in the constructor // if there is only one dive per page row we pass fitNotesToHeight to be almost half the page height QPointer<QTableView> table(createProfileTable(&model, scaledW, (divesPerRow == 1) ? scaledH * 0.45 : 0.0)); // profilePrintTableMaxH updates after the table is created const int tableH = profilePrintTableMaxH; // resize the profile widget profile->resize(scaledW, scaledH - tableH - padPT); // offset table or profile on top int yOffsetProfile = 0, yOffsetTable = 0; if (printOptions->notes_up) yOffsetProfile = tableH + padPT; else yOffsetTable = scaledH - tableH; // plot the dives at specific rows and columns on the page for_each_dive (i, dive) { if (!dive->selected && printOptions->print_selected) continue; if (col == divesPerColumn) { col = 0; row++; if (row == divesPerRow) { row = 0; printer->newPage(); } } // draw a profile QTransform origTransform = painter.transform(); painter.translate((scaledW + padW) * col, (scaledH + padH) * row + yOffsetProfile); profile->plotDive(dive, true); // make sure the profile is actually redrawn #ifdef Q_OS_LINUX // on Linux there is a vector line bug (big lines in PDF), which forces us to render to QImage QImage image(scaledW, scaledH - tableH - padPT, QImage::Format_ARGB32); QPainter imgPainter(&image); imgPainter.setRenderHint(QPainter::Antialiasing); imgPainter.setRenderHint(QPainter::SmoothPixmapTransform); profile->render(&imgPainter, QRect(0, 0, scaledW, scaledH - tableH - padPT)); imgPainter.end(); painter.drawImage(image.rect(),image); #else // for other OS we can try rendering the profile as vector profile->render(&painter, QRect(0, 0, scaledW, scaledH - tableH - padPT)); #endif painter.setTransform(origTransform); // draw a table QPicture pic; QPainter picPainter; painter.translate((scaledW + padW) * col, (scaledH + padH) * row + yOffsetTable); model.setDive(dive); picPainter.begin(&pic); table->render(&picPainter); picPainter.end(); painter.drawPicture(QPoint(0,0), pic); painter.setTransform(origTransform); col++; printed++; emit signalProgress((printed * 100) / total); } // cleanup painter.end(); profile->setFrameStyle(profileFrameStyle); profile->setPrintMode(false); profile->resize(originalSize); // we need to force a redraw of the profile so it switches back from print mode profile->plotDive(0, true); // re-enable animations prefs.animation_speed = animationOriginal; }
void ProjectorWindow::paintEvent(QPaintEvent* ev) { // This event is called when the widget is asked to repaint itself // All of our custom painter logic should go in here. // Painter to paint the window QPainter painter; // Hold on to the normal (transparent) brush QBrush normalBrush; // List of data HTMLs QStringList dataHtml; // Pens (i.e. line drawing settings for the painter) QPen ballPen = QPen((QColor(0, 0, 255))); ballPen.setWidthF(mPointThickness); QPen kfSeenPen = QPen((QColor(255,0,0))); kfSeenPen.setWidthF(mPointThickness); QPen kfMissPen = QPen((QColor(255,255,0))); kfMissPen.setWidthF(mPointThickness); QPen markPen = QPen((QColor(255,255,255))); markPen.setWidthF(mPointThickness); QPen fitPen = QPen((QColor(255,0,255))); fitPen.setWidthF(mFitThickness); QPen fitLockPen = QPen(mColorFitLock); fitLockPen.setWidthF(mFitThickness); // We have to begin painting. Remember to end. painter.begin(this); normalBrush = painter.brush(); // This brush is the background color of the widget. // Fill the window in case. QBrush background = QBrush(QColor(0,0,0)); painter.fillRect(ev->rect(), background); // Draw the ball indicators on the projector screen painter.setPen(ballPen); QList<TrackingBall>::const_iterator ballsIter; for (ballsIter = mBalls.begin(); ballsIter != mBalls.end(); ++ballsIter) { painter.drawEllipse( (QPoint)(*ballsIter).center()*2, (int)(*ballsIter).r()*2, (int)(*ballsIter).r()*2); } // Draw the KF prediction indicators on the screen QList<KFPrediction>::const_iterator predsIter; for (predsIter = mPreds.begin(); predsIter != mPreds.end(); ++predsIter) { // The color of the indicator depends on if the ball was actually // seen on this frame or not if (((*predsIter).seen() || !mColorMiss)) { painter.setPen(kfSeenPen); } else { painter.setPen(kfMissPen); } // Draw the bounding box of the predicted ball if (mVerboseKF) { painter.drawRect(relRectToWindow((*predsIter).bbox())); } else { painter.drawEllipse(QRectF(relPointToWindow( (*predsIter).bbox().center()) - QPointF(mPointRadius/2,mPointRadius/2), QSizeF(mPointRadius,mPointRadius))); } if (mShowJet) { // Draw the predicted velocities of the predicted ball painter.drawLine(relPointToWindow((*predsIter).bbox().center()), relPointToWindow( (*predsIter).bbox().center() + ((QPointF)(*predsIter).jet() * (*predsIter).dt()))); } } int j; double t0; j = 0; // Draw the predicted flight trajectory of the ball if (mShowParam || mShowFit) { double a, b, A, B, C, U, V, W; // x(t) = at + b a = mFitLineX[1]; b = mFitLineX[0]; // y(t) = At^2 + Bt + C A = mFitParabolaY[2]; B = mFitParabolaY[1]; C = mFitParabolaY[0]; // y(x) = Ux^2 + Vx + W U = A/a/a; V = B/a - 2*A*b/a/a; W = A*b*b/a/a - B*b/a + C; // Show the fit parabola if (mShowParabola) { if (mFitLocked) { painter.setPen(fitLockPen); } else { painter.setPen(fitPen); } QPointF p1(0, W); QPointF p2(mProjSize.width(), U*mProjSize.width()*mProjSize.width() + V*mProjSize.width() + W); QPointF c(0.5*mProjSize.width(), W + .5*mProjSize.width()*V); QPainterPath fitPath(relPointToWindow(p1)); fitPath.quadTo(relPointToWindow(c), relPointToWindow(p2)); painter.drawPath(fitPath); } // Draw the predicted y(t) and x(t) equation if (mShowParam) { dataHtml << QString("y(t) = %1 t<sup>2</sup> + %2 t + %3") .arg(A, 0, 'f', 3) .arg(B, 0, 'f', 3) .arg(C, 0, 'f', 3) << QString("x(t) = %1 t + %2") .arg(a, 0, 'f', 3) .arg(b, 0, 'f', 3); } } if (!mMarkedPoints.empty()) { t0 = mMarkedPoints.at(0).t(); } //QStringList markHtml; QRectF markRect; QFont markFont = painter.font(); markFont.setPointSize(mFontSize); int mMarkRadius = mPointRadius*0.8; // Draw marked points painter.setFont(markFont); for (predsIter = mMarkedPoints.begin(); predsIter != mMarkedPoints.end(); ++predsIter) { painter.setPen(markPen); dataHtml << QString("%1: (%2, %3, %4)") .arg(j) .arg(predsIter->t()-t0, 0, 'f', 3) .arg(predsIter->bbox().center().x(), 0, 'f', 3) .arg(predsIter->bbox().center().y(), 0, 'f', 3); markRect = QRectF((relPointToWindow( (*predsIter).bbox().center()) - QPointF(mMarkRadius/2,mMarkRadius/2)), QSizeF(mMarkRadius,mMarkRadius)); painter.setBrush(background); painter.drawEllipse(markRect); painter.setBrush(normalBrush); painter.drawText(markRect, Qt::AlignCenter|Qt::TextDontClip, QString("%1").arg(j)); j++; } if (!dataHtml.empty()) { QTextDocument td; td.setDefaultStyleSheet( QString("body {" " color: rgb(255,255,255);" " font-size: %1pt;" "}") .arg(mFontSize)); td.setHtml(QString( "<body>%1</body>") .arg(dataHtml.join("<br>")) ); td.drawContents(&painter); } painter.end(); }
void PaperWalletDialog::on_printButton_clicked() { QPrinter printer(QPrinter::HighResolution); QPrintDialog *qpd = new QPrintDialog(&printer, this); qpd->setPrintRange(QAbstractPrintDialog::AllPages); QList<QString> recipientPubKeyHashes; if ( qpd->exec() != QDialog::Accepted ) { return; } // Hardcode these values printer.setOrientation(QPrinter::Portrait); printer.setPaperSize(QPrinter::A4); printer.setFullPage(true); QPainter painter; if (! painter.begin(&printer)) { // failed to open file QMessageBox::critical(this, "Printing Error", tr("failed to open file, is it writable?"), QMessageBox::Ok, QMessageBox::Ok); return; } int walletCount = ui->walletCount->currentIndex() + 1; int walletsPerPage = 4; int pageHeight = printer.pageRect().height() - PAPER_WALLET_PAGE_MARGIN; int walletHeight = ui->paperTemplate->height(); double computedWalletHeight = 0.9 * pageHeight / walletsPerPage; double scale = computedWalletHeight / walletHeight; double walletPadding = pageHeight * 0.05 / (walletsPerPage - 1) / scale; QRegion walletRegion = QRegion(ui->paperTemplate->x(), ui->paperTemplate->y(), ui->paperTemplate->width(), ui->paperTemplate->height()); painter.scale(scale, scale); for(int i = 0; i < walletCount; i++) { this->on_getNewAddress_clicked(); QPoint point = QPoint(PAPER_WALLET_PAGE_MARGIN, (PAPER_WALLET_PAGE_MARGIN / 2) + ( i % walletsPerPage ) * (walletHeight + walletPadding)); this->render(&painter, point, walletRegion); recipientPubKeyHashes.append(ui->addressText->text()); if ( i % walletsPerPage == ( walletsPerPage - 1 ) ) { printer.newPage(); } } painter.end(); #ifdef ENABLE_WALLET QStringList formatted; WalletModelTransaction *tx; while( true ) { bool ok; // Ask for an amount to send to each paper wallet. It might be better to try to use the BitcoinAmountField, but this works fine. double amountInput = QInputDialog::getDouble(this, tr("Load Paper Wallets"), tr("Please wait for wallets to print and verify readability.<br/>Enter the number of LIMX you wish to send to each wallet:"), 0, 0, 2147483647, 8, &ok); if(!ok) { return; } // WalletModel::UnlockContext ctx(this->model->requestUnlock()); WalletModel::UnlockContext ctx(model->requestUnlock(true)); if(!ctx.isValid()) { return; } QList<SendCoinsRecipient> recipients; quint64 amount = (quint64) ( amountInput * COIN ); foreach(const QString &dest, recipientPubKeyHashes) { recipients.append(SendCoinsRecipient(dest,tr("Paper wallet %1").arg(dest), amount,"")); formatted.append(tr("<b>%1</b> to Paper Wallet <span style='font-family: monospace;'>%2</span>").arg(QString::number(amountInput, 'f', 8), GUIUtil::HtmlEscape(dest))); } tx = new WalletModelTransaction(recipients); WalletModel::SendCoinsReturn prepareStatus; if (this->model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled prepareStatus = this->model->prepareTransaction(*tx, CoinControlDialog::coinControl); else prepareStatus = this->model->prepareTransaction(*tx); if (prepareStatus.status == WalletModel::InvalidAddress) { QMessageBox::critical(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); } else if (prepareStatus.status == WalletModel::InvalidAmount) { QMessageBox::critical(this, tr("Send Coins"), tr("The amount to pay must be larger than 0"), QMessageBox::Ok, QMessageBox::Ok); } else if (prepareStatus.status == WalletModel::AmountExceedsBalance) { QMessageBox::critical(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); } else if (prepareStatus.status == WalletModel::AmountWithFeeExceedsBalance) { QMessageBox::critical(this, tr("Send Coins"), tr("The total exceeds your balance when the transaction fee is included"), QMessageBox::Ok, QMessageBox::Ok); } else if (prepareStatus.status == WalletModel::DuplicateAddress) { QMessageBox::critical(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); } else if (prepareStatus.status == WalletModel::TransactionCreationFailed) { QMessageBox::critical(this, tr("Send Coins"), tr("Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); } else if (prepareStatus.status == WalletModel::OK) { break; } else { delete tx; return; } }
bool QtPrinterTableView::print() { Q_D(QtPrinterTableView); if (! d->printer->isValid()) { qWarning() << "QtPrinterTableView::print: printer not valid, please setup the printer before calling print"; return false; } // next use a view just for the filling of the options... QGraphicsScene scene; QtGraphicsTableView view; scene.addItem(&view); view.setModel(d->model); class QTableHeaderDataProvider2 : public QtGraphicsHeaderDataProvider { public: QTableHeaderDataProvider2(QtTableModelInterface *model_) : model(model_) {} QHash<int,QVariant> data(int logicalIndex, const QList<int> &roles) const { // ### call the model - temporary implementation QHash<int,QVariant> hash; for (int i = 0; i < roles.count(); ++i) if (roles.at(i) == Qt::DisplayRole) hash.insert(Qt::DisplayRole, logicalIndex + 1); return hash; } QtTableModelInterface *model; }; if (d->horizontalHeader) { QtGraphicsHeader *header = new QtGraphicsHeader(Qt::Horizontal, &view); header->setDataProvider(new QTableHeaderDataProvider2(d->model)); header->copySections(*d->horizontalHeader); view.setHorizontalHeader(header); } if (d->verticalHeader) { QtGraphicsHeader *header = new QtGraphicsHeader(Qt::Vertical, &view); header->setDataProvider(new QTableHeaderDataProvider2(d->model)); header->copySections(*d->verticalHeader); view.setVerticalHeader(header); } QPainter painter; if (!painter.begin(d->printer)) { qWarning() << "QtPrinterTableView::print: printer fails to begin(), sorry can't print"; return false; } // re-layout the header footer to the current page size. if (d->header) { d->header->documentLayout()->setPaintDevice(d->printer); d->header->setPageSize(d->printer->pageRect().size()); } if (d->footer) { d->footer->documentLayout()->setPaintDevice(d->printer); d->footer->setPageSize(d->printer->pageRect().size()); } const qreal headerSize = d->printHeader(painter); const qreal footerSize = d->printFooter(painter); const bool vertical = d->orientation == Qt::Vertical; const qreal scaleX = d->printer->logicalDpiX() / (qreal) qt_defaultDpiX(); const qreal scaleY = d->printer->logicalDpiY() / (qreal) qt_defaultDpiY(); painter.scale(scaleX, scaleY); const QRect rect = d->printer->pageRect(); QSizeF visibleSize(rect.width() / scaleX, rect.height() / scaleY); if (vertical) visibleSize = QSizeF(visibleSize.width(), visibleSize.height() - headerSize - footerSize); else // then rotate it. visibleSize = QSizeF(visibleSize.height() - headerSize - footerSize, visibleSize.width()); view.setGeometry(0, 0, visibleSize.width(), visibleSize.height()); view.setHorizontalOffset(0); int row = 0; int column; bool first = true; qreal offsetInColumn = 0; // for those columns too wide and thus split over more than one page while (row < d->model->rowCount()) { column = 0; view.setFirstRow(row); qreal height = visibleSize.height(); while (true) { const qreal rowHeight = view.rowHeight(row); if (height - rowHeight < 0) break; if (row >= d->model->rowCount()) break; ++row; height -= rowHeight; } while (column < d->model->columnCount()) { if (!first) { d->printer->newPage(); d->printHeader(painter); d->printFooter(painter); } first = false; view.setFirstColumn(column); view.setHorizontalOffset(offsetInColumn); qreal width = visibleSize.width(); while (true) { const qreal columnWidth = view.columnWidth(column); if (width == visibleSize.width() && columnWidth - offsetInColumn > visibleSize.width()) { // the column doesn't fit on a page. Lets split it. offsetInColumn += visibleSize.width(); width = 0; break; } else if (offsetInColumn > 0) { // we still have a part of a split column to print! width -= columnWidth - offsetInColumn; offsetInColumn = 0; ++column; continue; } if (width - columnWidth + offsetInColumn < 0) break; if (column >= d->model->columnCount()) break; ++column; width -= columnWidth; } view.doLayout(); painter.save(); // for each page painter.translate(0, headerSize); if (!vertical) { painter.translate(0, visibleSize.width()); painter.rotate(-90); } #ifdef DEBUG_TABLES painter.setPen(QPen(QColor(Qt::green))); painter.drawRect(QRectF(0, 0, visibleSize.width() - width, visibleSize.height() - height)); #endif painter.setClipRect(QRectF(0, 0, visibleSize.width() - width, visibleSize.height() - height)); // find and paint children which are the cells QList<QGraphicsItem*> items = scene.items(view.rect()); QList<QGraphicsItem*>::Iterator iter = items.begin(); for (;iter != items.end(); ++iter) { QGraphicsItem *parent = *iter; while (parent != &view && parent != 0) // only draw children of our view parent = parent->parentItem(); if (parent == 0) continue; if (!(*iter)->isVisible()) continue; painter.save(); painter.translate((*iter)->mapToItem(&view, QPointF())); #ifdef DEBUG_TABLES QGraphicsWidget *w = dynamic_cast<QGraphicsWidget*>(*iter); if (w) { painter.save(); painter.setPen(QPen(QColor(Qt::red))); painter.drawRect(QRectF(QPointF(), w->size())); painter.restore(); } #endif (*iter)->paint(&painter, 0); painter.restore(); } painter.restore(); // for each page } } return true; }
QImage createImage(int width, int height) { QImage image(width, height, QImage::Format_RGB16); QPainter painter; QPen pen; pen.setStyle(Qt::NoPen); QBrush brush(Qt::blue); painter.begin(&image); painter.fillRect(image.rect(), brush); brush.setColor(Qt::white); painter.setPen(pen); painter.setBrush(brush); static const QPointF points1[3] = { QPointF(4, 4), QPointF(7, 4), QPointF(5.5, 1) }; static const QPointF points2[3] = { QPointF(1, 4), QPointF(7, 4), QPointF(10, 10) }; static const QPointF points3[3] = { QPointF(4, 4), QPointF(10, 4), QPointF(1, 10) }; painter.setWindow(0, 0, 10, 10); int x = 0; int y = 0; int starWidth = image.width()/3; int starHeight = image.height()/3; QRect rect(x, y, starWidth, starHeight); for (int i = 0; i < 9; ++i) { painter.setViewport(rect); painter.drawPolygon(points1, 3); painter.drawPolygon(points2, 3); painter.drawPolygon(points3, 3); if (i % 3 == 2) { y = y + starHeight; rect.moveTop(y); x = 0; rect.moveLeft(x); } else { x = x + starWidth; rect.moveLeft(x); } } painter.end(); return image; }
void MainWindow::on_pushButton_clicked() { QString Seq = ui->comboBox->currentText(); QPrinter printer; QPrintDialog *dialog = new QPrintDialog(&printer, this); dialog->setWindowTitle(tr("Print Document")); // if (editor->textCursor().hasSelection()) // dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection); if (dialog->exec() != QDialog::Accepted) return; QPainter painter; painter.begin(&printer); QString text; int rows = ui->tableWidget->rowCount(); int n = 100; painter.drawText(100, n, 500, 500, Qt::AlignLeft|Qt::AlignTop, Seq); n+=60; for (int i =0; i<rows; i++) { text = ui->tableWidget->item(i,0)->text() + " " + ui->tableWidget->item(i,1)->text(); painter.drawText(100, n, 500, 500, Qt::AlignLeft|Qt::AlignTop, text); n+=20; } for (int i =0; i<4; i++) { text = " "; painter.drawText(100, n, 500, 500, Qt::AlignLeft|Qt::AlignTop, text); n+=20; } for (int i =0; i<rows; i++) { text = ui->tableWidget->item(i,2)->text() + " " + ui->tableWidget->item(i,3)->text(); qDebug()<<text; painter.drawText(100, n, 500, 500, Qt::AlignLeft|Qt::AlignTop, text); n+=20; } painter.end(); }
void QtOutline2Rasterizer::rasterize(RasterizedOutline2 &poly, float scale, int rast_i, int rotationNum, int cellSize) { float rotRad = M_PI*2.0f*float(rast_i) / float(rotationNum); //get polygon's BB, rotated according to the input parameter Box2f bb; vector<Point2f> pointvec = poly.getPoints(); for(size_t i=0;i<pointvec.size();++i) { Point2f pp=pointvec[i]; pp.Rotate(rotRad); bb.Add(pp); } ///CREATE ITS GRID. The grid has to be a multiple of CELLSIZE because this grid's cells have size CELLSIZE //we'll make so that sizeX and sizeY are multiples of CELLSIZE: //1) we round it to the next integer //2) add the number which makes it a multiple of CELLSIZE (only if it's not multiple already) int sizeX = (int)ceil(bb.DimX()*scale); int sizeY = (int)ceil(bb.DimY()*scale); if (sizeX % cellSize != 0) sizeX += (cellSize - ((int)ceil(bb.DimX()*scale) % cellSize)); if (sizeY % cellSize != 0) sizeY += (cellSize - ((int)ceil(bb.DimY()*scale) % cellSize)); //security measure: add a dummy column/row thus making the image bigger, and crop it afterwards //(if it hasn't been filled with anything) //this is due to the fact that if we have a rectangle which has bb 39.xxx wide, then it won't fit in a 40px wide QImage!! The right side will go outside of the image!! :/ sizeX+=cellSize; sizeY+=cellSize; QImage img(sizeX,sizeY,QImage::Format_RGB32); QColor backgroundColor(Qt::transparent); img.fill(backgroundColor); ///SETUP OF DRAWING PROCEDURE QPainter painter; painter.begin(&img); QBrush br; br.setStyle(Qt::SolidPattern); QPen qp; qp.setWidthF(0); qp.setColor(Qt::yellow); painter.setBrush(br); painter.setPen(qp); painter.resetTransform(); painter.translate(QPointF(-(bb.min.X()*scale) , -(bb.min.Y()*scale) )); painter.rotate(math::ToDeg(rotRad)); painter.scale(scale,scale); //create the polygon to print it QVector<QPointF> points; vector<Point2f> newpoints = poly.getPoints(); for (size_t i = 0; i < newpoints.size(); i++) { points.push_back(QPointF(newpoints[i].X(), newpoints[i].Y())); } painter.drawPolygon(QPolygonF(points)); //CROPPING: it is enough to check for the (end - cellSize - 1)th row/col of pixels, if they're all black we can eliminate the last 8columns/rows of pixels bool cropX = true; bool cropY = true; for (int j=0; j<img.height(); j++) { const uchar* line = img.scanLine(j); if (j == img.height() - (cellSize - 1) - 1 ) { for (int x=0; x<img.width(); x++) { if (((QRgb*)line)[x] != backgroundColor.rgb()) { cropY = false; break; } } } else { if (((QRgb*)line)[img.width() - (cellSize - 1) - 1] != backgroundColor.rgb()) { cropX = false; break; } } if (!cropY) break; } if (cropX || cropY) { painter.end(); img = img.copy(0, 0, img.width() - cellSize * cropX, img.height() - cellSize * cropY); painter.begin(&img); painter.setBrush(br); painter.setPen(qp); } //draw the poly for the second time, this time it is centered to the image img.fill(backgroundColor); painter.resetTransform(); painter.translate(QPointF(-(bb.min.X()*scale) + (img.width() - ceil(bb.DimX()*scale))/2.0, -(bb.min.Y()*scale) + (img.height() - ceil(bb.DimY()*scale))/2.0)); painter.rotate(math::ToDeg(rotRad)); painter.scale(scale,scale); //create the polygon to print it QVector<QPointF> points2; vector<Point2f> newpoints2 = poly.getPoints(); for (size_t i = 0; i < newpoints2.size(); i++) { points2.push_back(QPointF(newpoints2[i].X(), newpoints2[i].Y())); } painter.drawPolygon(QPolygonF(points2)); //create the first grid, which will then be rotated 3 times. //we will reuse this grid to create the rasterizations corresponding to this one rotated by 90/180/270° vector<vector<int> > tetrisGrid; QRgb yellow = QColor(Qt::yellow).rgb(); int gridWidth = img.width() / cellSize; int gridHeight = img.height() / cellSize; int x = 0; tetrisGrid.resize(gridHeight); for (int k = 0; k < gridHeight; k++) { tetrisGrid[k].resize(gridWidth, 0); } for (int y = 0; y < img.height(); y++) { int gridY = y / cellSize; const uchar* line = img.scanLine(y); x = 0; int gridX = 0; while(x < img.width()) { gridX = x/cellSize; if (tetrisGrid[gridY][gridX] == 1) { x+= cellSize - (x % cellSize); //align with the next x continue; } if (((QRgb*)line)[x] == yellow) tetrisGrid[gridY][gridX] = 1; ++x; } } //create the 4 rasterizations (one every 90°) using the discrete representation grid we've just created int rotationOffset = rotationNum/4; for (int j = 0; j < 4; j++) { if (j != 0) { tetrisGrid = rotateGridCWise(tetrisGrid); } //add the grid to the poly's vector of grids poly.getGrids(rast_i + rotationOffset*j) = tetrisGrid; //initializes bottom/left/deltaX/deltaY vectors of the poly, for the current rasterization poly.initFromGrid(rast_i + rotationOffset*j); } painter.end(); }
void TransportButton::drawMask(QPixmap *cap) { QPolygon triangle=QPolygon(3); QPainter b; QBitmap *bitmap=new QBitmap(size()); int edge; if(height()<width()) { edge=height(); } else { edge=width(); } cap->resize(size()); b.begin(bitmap); b.fillRect(0,0,size().width(),size().height(),QColor(Qt::color0)); b.setPen(QColor(Qt::color1)); b.setBrush(QColor(Qt::color1)); switch(button_type) { case TransportButton::Play: triangle.setPoint(0,width()/2-(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2+(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::Stop: b.fillRect(width()/2-edge*3/10,height()/2-edge*3/10, edge*3/5,edge*3/5,QColor(Qt::color1)); break; case TransportButton::Record: b.drawEllipse(width()/2-(3*edge)/10,height()/2-(3*edge)/10, (3*edge)/5,(3*edge)/5); break; case TransportButton::FastForward: triangle.setPoint(0,width()/2-(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2+(3*edge)/10); b.drawPolygon(triangle); triangle.setPoint(0,width()/2,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()/2); triangle.setPoint(2,width()/2,height()/2+(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::Rewind: triangle.setPoint(0,width()/2+(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2,height()/2); triangle.setPoint(2,width()/2+(3*edge)/10,height()/2+(3*edge)/10); b.drawPolygon(triangle); triangle.setPoint(0,width()/2,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2-(3*edge)/10,height()/2); triangle.setPoint(2,width()/2,height()/2+(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::Eject: triangle.setPoint(0,width()/2,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2); b.drawPolygon(triangle); b.fillRect(width()/2-(3*edge)/10,height()/2+edge/10, (3*edge)/5,edge/5,QColor(Qt::color1)); break; case TransportButton::Pause: b.fillRect(width()/2-(3*edge)/10,height()/2-(3*edge)/10, (3*edge)/15,(3*edge)/5,QColor(Qt::color1)); b.fillRect(width()/2+(3*edge)/30,height()/2-(3*edge)/10, (3*edge)/15,(3*edge)/5,QColor(Qt::color1)); break; case TransportButton::PlayFrom: b.fillRect(width()/2-(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(Qt::color1)); triangle.setPoint(0,width()/2-(2*edge)/10+1,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10+1,height()/2); triangle.setPoint(2,width()/2-(2*edge)/10+1,height()/2+(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::PlayBetween: b.fillRect(width()/2-(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(Qt::color1)); b.fillRect(width()/2+(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(Qt::color1)); triangle.setPoint(0,width()/2-(2*edge)/10+1,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(2*edge)/10+1,height()/2); triangle.setPoint(2,width()/2-(2*edge)/10+1,height()/2+(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::Loop: // b.moveTo(width()/2-(2*edge)/10+1,height()/2+(edge)/4); // b.moveTo(width()/2+(edge)/10+1,height()/2-edge/10); // b.moveTo(width()/2-(2*edge)/10+1,height()/2+(edge)/4); b.drawArc(width()/6,height()/2-edge/9,2*width()/3, height()/3+edge/10,1440,5760); triangle.setPoint(0,width()/2-(2*edge)/10+1,height()/2-(edge)/4); triangle.setPoint(1,width()/2+(edge)/10+1,height()/2-edge/10); triangle.setPoint(2,width()/2-(2*edge)/10+1,height()/2+edge/20); b.drawPolygon(triangle); break; case TransportButton::Up: triangle.setPoint(0,width()/2,(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()-(3*edge)/10); triangle.setPoint(2,width()/2-(3*edge)/10,height()-(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::Down: triangle.setPoint(0,width()/2,height()-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,(3*edge)/10); triangle.setPoint(2,width()/2-(3*edge)/10,(3*edge)/10); b.drawPolygon(triangle); break; case TransportButton::PlayTo: b.fillRect(width()/2+(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(Qt::color1)); triangle.setPoint(0,width()/2-(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(2*edge)/10+1,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2+(3*edge)/10); b.drawPolygon(triangle); break; default: b.fillRect(0,0,width(),height(),QColor(Qt::color1)); } b.end(); cap->setMask(*bitmap); delete bitmap; }
void TemplateImage::drawOntoTemplateImpl(MapCoordF* coords, int num_coords, QColor color, float width) { QPointF* points; QRect radius_bbox; int draw_iterations = 1; bool all_coords_equal = true; for (int i = 1; i < num_coords; ++i) { if (coords[i] != coords[i-1]) { all_coords_equal = false; break; } } // Special case for points because drawPolyline() draws nothing in this case. // drawPoint() is also unsuitable because it aligns the point to the closest pixel. // drawEllipse() in the tested Qt version (5.1.1) seems to have a bug with antialiasing here. if (all_coords_equal) { const qreal ring_radius = 0.8; const qreal width_factor = 2.0; draw_iterations = 2; width *= width_factor; num_coords = 5; points = new QPointF[5]; points[0] = mapToTemplate(coords[0]) + QPointF(image.width() * 0.5f, image.height() * 0.5f); points[1] = points[0] + QPointF(ring_radius, 0); points[2] = points[0] + QPointF(0, ring_radius); points[3] = points[0] + QPointF(-ring_radius, 0); points[4] = points[0] + QPointF(0, -ring_radius); points[0] = points[4]; radius_bbox = QRect( qFloor(points[3].x() - width - 1), qFloor(points[4].y() - width - 1), qCeil(2 * ring_radius + 2*width + 2.5f), qCeil(2 * ring_radius + 2*width + 2.5f) ); } else { points = new QPointF[num_coords]; QRectF bbox; for (int i = 0; i < num_coords; ++i) { points[i] = mapToTemplate(coords[i]) + QPointF(image.width() * 0.5f, image.height() * 0.5f); rectIncludeSafe(bbox, points[i]); } radius_bbox = QRect( qFloor(bbox.left() - width - 1), qFloor(bbox.top() - width - 1), qCeil(bbox.width() + 2*width + 2.5f), qCeil(bbox.height() + 2*width + 2.5f) ); radius_bbox = radius_bbox.intersected(QRect(0, 0, image.width(), image.height())); } // Create undo step DrawOnImageUndoStep undo_step; undo_step.x = radius_bbox.left(); undo_step.y = radius_bbox.top(); undo_step.image = image.copy(radius_bbox); addUndoStep(undo_step); // This conversion is to prevent a very strange bug where the behavior of the // default QPainter composition mode seems to be incorrect for images which are // loaded from a file without alpha and then painted over with the eraser if (color.alpha() == 0 && image.format() != QImage::Format_ARGB32_Premultiplied) image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); QPainter painter; painter.begin(&image); if (color.alpha() == 0) painter.setCompositionMode(QPainter::CompositionMode_Clear); else painter.setOpacity(color.alphaF()); QPen pen(color); pen.setWidthF(width); pen.setCapStyle(Qt::RoundCap); pen.setJoinStyle(Qt::RoundJoin); painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing); for (int i = 0; i < draw_iterations; ++ i) painter.drawPolyline(points, num_coords); painter.end(); delete[] points; }
void TransportButton::drawOffCap() { QPainter p; QPolygon triangle=QPolygon(3); int edge; if(height()<width()) { edge=height(); } else { edge=width(); } drawMask(off_cap); p.begin(off_cap); p.setPen(QColor(Qt::black)); p.setBrush(QColor(Qt::black)); switch(button_type) { case TransportButton::Play: triangle.setPoint(0,width()/2-(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(3*edge)/10,height()/2+(3*edge)/10, width()/2-(3*edge)/10,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2-(3*edge)/10,height()/2-(3*edge)/10, width()/2+(3*edge)/10,height()/2); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(3*edge)/10,height()/2, width()/2-(3*edge)/10,height()/2+(3*edge)/10); break; case TransportButton::Stop: p.fillRect(width()/2-edge*3/10,height()/2-edge*3/10, edge*3/5,edge*3/5,QColor(colorGroup().shadow())); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-edge*3/10,height()/2+edge*3/10, width()/2-edge*3/10,height()/2-edge*3/10); p.drawLine(width()/2-edge*3/10,height()/2-edge*3/10, width()/2+edge*3/10,height()/2-edge*3/10); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+edge*3/10,height()/2-edge*3/10, width()/2+edge*3/10,height()/2+edge*3/10); p.drawLine(width()/2+edge*3/10,height()/2+edge*3/10, width()/2-edge*3/10,height()/2+edge*3/10); break; case TransportButton::Record: p.setPen(QColor(Qt::darkRed)); p.setBrush(QColor(Qt::darkRed)); p.drawEllipse(width()/2-(3*edge)/10,height()/2-(3*edge)/10, (3*edge)/5,(3*edge)/5); break; case TransportButton::FastForward: triangle.setPoint(0,width()/2-(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(3*edge)/10,height()/2+(3*edge)/10, width()/2-(3*edge)/10,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2-(3*edge)/10,height()/2-(3*edge)/10, width()/2,height()/2); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2,height()/2, width()/2-(3*edge)/10,height()/2+(3*edge)/10); triangle.setPoint(0,width()/2,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()/2); triangle.setPoint(2,width()/2,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2,height()/2+(3*edge)/10, width()/2,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2,height()/2-(3*edge)/10, width()/2+(3*edge)/10,height()/2); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(3*edge)/10,height()/2, width()/2,height()/2+(3*edge)/10); break; case TransportButton::Rewind: triangle.setPoint(0,width()/2+(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2,height()/2); triangle.setPoint(2,width()/2+(3*edge)/10,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2+(3*edge)/10,height()/2-(3*edge)/10, width()/2,height()/2); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2,height()/2, width()/2+(3*edge)/10,height()/2+(3*edge)/10); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(3*edge)/10,height()/2+(3*edge)/10, width()/2+(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(0,width()/2,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2-(3*edge)/10,height()/2); triangle.setPoint(2,width()/2,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2,height()/2-(3*edge)/10, width()/2-(3*edge)/10,height()/2); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2-(3*edge)/10,height()/2, width()/2,height()/2+(3*edge)/10); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2,height()/2+(3*edge)/10, width()/2,height()/2-(3*edge)/10); break; case TransportButton::Eject: triangle.setPoint(0,width()/2,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2); p.drawPolygon(triangle); p.fillRect(width()/2-(3*edge)/10,height()/2+edge/10, (3*edge)/5,edge/5,QColor(Qt::black)); break; case TransportButton::Pause: p.fillRect(width()/2-(3*edge)/10,height()/2-(3*edge)/10, (3*edge)/15,(3*edge)/5,QColor(Qt::black)); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(3*edge)/10,height()/2+(3*edge)/10, width()/2-(3*edge)/10,height()/2+(3*edge)/10); p.drawLine(width()/2-(3*edge)/10,height()/2+(3*edge)/10, width()/2-(3*edge)/10+(3*edge)/15,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2-(3*edge)/10+(3*edge)/15,height()/2-(3*edge)/10, width()/2-(3*edge)/10+(3*edge)/15,height()/2+(3*edge)/10); p.drawLine(width()/2-(3*edge)/10+(3*edge)/15,height()/2+(3*edge)/10, width()/2-(3*edge)/10,height()/2+(3*edge)/10); p.fillRect(width()/2+(3*edge)/30,height()/2-(3*edge)/10, (3*edge)/15,(3*edge)/5,QColor(Qt::black)); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2+(3*edge)/30,height()/2+(3*edge)/10, width()/2+(3*edge)/30,height()/2-(3*edge)/10); p.drawLine(width()/2+(3*edge)/30,height()/2-(3*edge)/10, width()/2+(3*edge)/10,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(3*edge)/10,height()/2-(3*edge)/10, width()/2+(3*edge)/10,height()/2+(3*edge)/10); p.drawLine(width()/2+(3*edge)/10,height()/2+(3*edge)/10, width()/2+(3*edge)/30,height()/2+(3*edge)/10); break; case TransportButton::PlayFrom: p.fillRect(width()/2-(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(accent_color)); triangle.setPoint(0,width()/2-(2*edge)/10+1,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10+1,height()/2); triangle.setPoint(2,width()/2-(2*edge)/10+1,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(2*edge)/10+1,height()/2+(3*edge)/10, width()/2-(2*edge)/10+1,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2-(2*edge)/10+1,height()/2-(3*edge)/10, width()/2+(3*edge)/10+1,height()/2); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(3*edge)/10+1,height()/2, width()/2-(2*edge)/10+1,height()/2+(3*edge)/10); break; case TransportButton::PlayBetween: p.fillRect(width()/2-(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(accent_color)); p.fillRect(width()/2+(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(accent_color)); triangle.setPoint(0,width()/2-(2*edge)/10+1,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(2*edge)/10+1,height()/2); triangle.setPoint(2,width()/2-(2*edge)/10+1,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(2*edge)/10+1,height()/2+(3*edge)/10, width()/2-(2*edge)/10+1,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2-(2*edge)/10+1,height()/2-(3*edge)/10, width()/2+(2*edge)/10+1,height()/2); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(2*edge)/10+1,height()/2, width()/2-(2*edge)/10+1,height()/2+(3*edge)/10); break; case TransportButton::Loop: triangle.setPoint(0,width()/2-(2*edge)/10+1,height()/2-(edge)/4); triangle.setPoint(1,width()/2+(edge)/10+1,height()/2-edge/10); triangle.setPoint(2,width()/2-(2*edge)/10+1,height()/2+edge/20); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(2*edge)/10+1,height()/2+(edge)/4, width()/2+(edge)/10+1,height()/2-edge/10); p.setPen(QColor(colorGroup().dark())); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(edge)/10+1,height()/2-edge/10, width()/2-(2*edge)/10+1,height()/2+(edge)/4); p.setPen(QColor(colorGroup().shadow())); p.drawArc(width()/6,height()/2-edge/9,2*width()/3, height()/3+edge/10,1440,5760); break; case TransportButton::Up: triangle.setPoint(0,width()/2,(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,height()-(3*edge)/10); triangle.setPoint(2,width()/2-(3*edge)/10,height()-(3*edge)/10); p.drawPolygon(triangle); break; case TransportButton::Down: triangle.setPoint(0,width()/2,height()-(3*edge)/10); triangle.setPoint(1,width()/2+(3*edge)/10,(3*edge)/10); triangle.setPoint(2,width()/2-(3*edge)/10,(3*edge)/10); p.drawPolygon(triangle); break; case TransportButton::PlayTo: p.fillRect(width()/2+(3*edge)/10,height()/2-(3*edge)/10, 3,(3*edge)/5,QBrush(accent_color)); triangle.setPoint(0,width()/2-(3*edge)/10,height()/2-(3*edge)/10); triangle.setPoint(1,width()/2+(2*edge)/10+1,height()/2); triangle.setPoint(2,width()/2-(3*edge)/10,height()/2+(3*edge)/10); p.drawPolygon(triangle); p.setPen(QColor(colorGroup().shadow())); p.drawLine(width()/2-(3*edge)/10,height()/2+(3*edge)/10, width()/2-(3*edge)/10,height()/2-(3*edge)/10); p.setPen(QColor(colorGroup().dark())); p.drawLine(width()/2-(3*edge)/10,height()/2-(3*edge)/10, width()/2+(2*edge)/10+1,height()/2); p.setPen(QColor(colorGroup().light())); p.drawLine(width()/2+(2*edge)/10+1,height()/2, width()/2-(3*edge)/10,height()/2+(3*edge)/10); break; } p.end(); }
void WaveformRenderMark::generateMarkImage(WaveformMark* pMark) { const WaveformMarkProperties& markProperties = pMark->getProperties(); // Load the pixmap from file -- takes precedence over text. if (!markProperties.m_pixmapPath.isEmpty()) { QString path = markProperties.m_pixmapPath; QImage image = *WImageStore::getImage(path, scaleFactor()); //QImage image = QImage(path); // If loading the image didn't fail, then we're done. Otherwise fall // through and render a label. if (!image.isNull()) { pMark->m_image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); //WImageStore::correctImageColors(&pMark->m_image); return; } } QPainter painter; // If no text is provided, leave m_markImage as a null image if (!markProperties.m_text.isNull()) { // Determine mark text. QString label = markProperties.m_text; if (pMark->getHotCue() >= 0) { if (!label.isEmpty()) { label.prepend(": "); } label.prepend(QString::number(pMark->getHotCue() + 1)); if (label.size() > kMaxCueLabelLength) { label = label.left(kMaxCueLabelLength - 3) + "..."; } } //QFont font("Bitstream Vera Sans"); //QFont font("Helvetica"); QFont font; // Uses the application default font.setPointSizeF(10 * scaleFactor()); font.setStretch(100); font.setWeight(75); QFontMetrics metrics(font); //fixed margin ... QRect wordRect = metrics.tightBoundingRect(label); const int marginX = 1; const int marginY = 1; wordRect.moveTop(marginX + 1); wordRect.moveLeft(marginY + 1); wordRect.setHeight(wordRect.height() + (wordRect.height()%2)); wordRect.setWidth(wordRect.width() + (wordRect.width())%2); //even wordrect to have an even Image >> draw the line in the middle ! int labelRectWidth = wordRect.width() + 2 * marginX + 4; int labelRectHeight = wordRect.height() + 2 * marginY + 4 ; QRectF labelRect(0, 0, (float)labelRectWidth, (float)labelRectHeight); int width; int height; if (m_waveformRenderer->getOrientation() == Qt::Horizontal) { width = 2 * labelRectWidth + 1; height = m_waveformRenderer->getHeight(); } else { width = m_waveformRenderer->getWidth(); height = 2 * labelRectHeight + 1; } pMark->m_image = QImage(width, height, QImage::Format_ARGB32_Premultiplied); Qt::Alignment markAlignH = markProperties.m_align & Qt::AlignHorizontal_Mask; Qt::Alignment markAlignV = markProperties.m_align & Qt::AlignVertical_Mask; if (markAlignH == Qt::AlignHCenter) { labelRect.moveLeft((width - labelRectWidth) / 2); } else if (markAlignH == Qt::AlignRight) { labelRect.moveRight(width - 1); } if (markAlignV == Qt::AlignVCenter) { labelRect.moveTop((height - labelRectHeight) / 2); } else if (markAlignV == Qt::AlignBottom) { labelRect.moveBottom(height - 1); } // Fill with transparent pixels pMark->m_image.fill(QColor(0,0,0,0).rgba()); painter.begin(&pMark->m_image); painter.setRenderHint(QPainter::TextAntialiasing); painter.setWorldMatrixEnabled(false); // Draw marker lines if (m_waveformRenderer->getOrientation() == Qt::Horizontal) { int middle = width / 2; if (markAlignH == Qt::AlignHCenter) { if (labelRect.top() > 0) { painter.setPen(markProperties.fillColor()); painter.drawLine(middle, 0, middle, labelRect.top()); painter.setPen(markProperties.borderColor()); painter.drawLine(middle - 1, 0, middle - 1, labelRect.top()); painter.drawLine(middle + 1, 0, middle + 1, labelRect.top()); } if (labelRect.bottom() < height) { painter.setPen(markProperties.fillColor()); painter.drawLine(middle, labelRect.bottom(), middle, height); painter.setPen(markProperties.borderColor()); painter.drawLine(middle - 1, labelRect.bottom(), middle - 1, height); painter.drawLine(middle + 1, labelRect.bottom(), middle + 1, height); } } else { // AlignLeft || AlignRight painter.setPen(markProperties.fillColor()); painter.drawLine(middle, 0, middle, height); painter.setPen(markProperties.borderColor()); painter.drawLine(middle - 1, 0, middle - 1, height); painter.drawLine(middle + 1, 0, middle + 1, height); } } else { // Vertical int middle = height / 2; if (markAlignV == Qt::AlignVCenter) { if (labelRect.left() > 0) { painter.setPen(markProperties.fillColor()); painter.drawLine(0, middle, labelRect.left(), middle); painter.setPen(markProperties.borderColor()); painter.drawLine(0, middle - 1, labelRect.left(), middle - 1); painter.drawLine(0, middle + 1, labelRect.left(), middle + 1); } if (labelRect.right() < width) { painter.setPen(markProperties.fillColor()); painter.drawLine(labelRect.right(), middle, width, middle); painter.setPen(markProperties.borderColor()); painter.drawLine(labelRect.right(), middle - 1, width, middle - 1); painter.drawLine(labelRect.right(), middle + 1, width, middle + 1); } } else { // AlignTop || AlignBottom painter.setPen(markProperties.fillColor()); painter.drawLine(0, middle, width, middle); painter.setPen(markProperties.borderColor()); painter.drawLine(0, middle - 1, width, middle - 1); painter.drawLine(0, middle + 1, width, middle + 1); } } // Draw the label rect painter.setPen(markProperties.borderColor()); painter.setBrush(QBrush(markProperties.fillColor())); painter.drawRoundedRect(labelRect, 2.0, 2.0); // Draw text painter.setBrush(QBrush(QColor(0,0,0,0))); painter.setFont(font); painter.setPen(markProperties.labelColor()); painter.drawText(labelRect, Qt::AlignCenter, label); } else //no text draw triangle { float triangleSize = 9.0; float markLength = triangleSize + 1.0; float markBreadth = m_waveformRenderer->getBreadth(); int width, height; if (m_waveformRenderer->getOrientation() == Qt::Horizontal) { width = markLength; height = markBreadth; } else { width = markBreadth; height = markLength; } pMark->m_image = QImage(width, height, QImage::Format_ARGB32_Premultiplied); pMark->m_image.fill(QColor(0,0,0,0).rgba()); painter.begin(&pMark->m_image); painter.setRenderHint(QPainter::TextAntialiasing); painter.setWorldMatrixEnabled(false); // Rotate if drawing vertical waveforms if (m_waveformRenderer->getOrientation() == Qt::Vertical) { painter.setTransform(QTransform(0, 1, 1, 0, 0, 0)); } QColor triangleColor = markProperties.fillColor(); painter.setPen(QColor(0,0,0,0)); painter.setBrush(QBrush(triangleColor)); //vRince: again don't ask about the +-0.1 0.5 ... // just to make it nice in Qt ... QPolygonF triangle; triangle.append(QPointF(0.5,0)); triangle.append(QPointF(triangleSize+0.5,0)); triangle.append(QPointF(triangleSize*0.5 + 0.1, triangleSize*0.5)); painter.drawPolygon(triangle); triangle.clear(); triangle.append(QPointF(0.0,markBreadth)); triangle.append(QPointF(triangleSize+0.5,markBreadth)); triangle.append(QPointF(triangleSize*0.5 + 0.1, markBreadth - triangleSize*0.5 - 2.1)); painter.drawPolygon(triangle); //TODO vRince duplicated code make a method //draw line QColor lineColor = markProperties.fillColor(); painter.setPen(lineColor); float middle = markLength / 2.0; float lineTop = triangleSize * 0.5 + 1; float lineBottom = markBreadth - triangleSize * 0.5 - 1; painter.drawLine(middle, lineTop, middle, lineBottom); //other lines to increase contrast painter.setPen(QColor(0,0,0,100)); painter.drawLine(middle - 1, lineTop, middle - 1, lineBottom); painter.drawLine(middle + 1, lineTop, middle + 1, lineBottom); } }
void Label::update() { QPainter p; QFontMetrics fm(font_); QFontInfo info(font_); QRect r = QRect(QPoint(0, 0), fm.size(Qwt3D::SingleLine, text_));//fm.boundingRect(text_) misbehaviour under linux; #if QT_VERSION < 0x040000 r.moveBy(0, -r.top()); #else r.translate(0, -r.top()); #endif pm_ = QPixmap(r.width(), r.bottom()); if (pm_.isNull()){ // else crash under linux r = QRect(QPoint(0,0),fm.size(Qwt3D::SingleLine, QString(" "))); // draw empty space else //todo #if QT_VERSION < 0x040000 r.moveBy(0, -r.top()); #else r.translate(0, -r.top()); #endif pm_ = QPixmap(r.width(), r.bottom()); } if (plot() && plot()->isExportingVector()){ #if QT_VERSION >= 0x040000 Qwt3D::RGBA rgba = plot()->backgroundRGBAColor(); pm_.fill(GL2Qt(rgba.r, rgba.g, rgba.b)); #else pm_.fill(); #endif p.begin( &pm_ ); p.setFont( font_ ); p.setPen( Qt::SolidLine ); p.setPen( GL2Qt(color.r, color.g, color.b) ); p.drawText(0, r.height() - fm.descent() - 1, text_); p.end(); } else { QBitmap bm(pm_.width(),pm_.height()); #if QT_VERSION >= 0x040000 && defined(Q_WS_X11) bm.fill(Qt::white); p.begin( &bm ); p.setPen(Qt::black); p.setFont(font_); p.drawText(0,r.height() - fm.descent() -1 , text_); p.end(); pm_.setMask(bm); // avoids uninitialized areas in some cases pm_.fill(Qt::white); p.begin( &pm_ ); p.setFont( font_ ); p.setPen( Qt::SolidLine ); p.setPen( GL2Qt(color.r, color.g, color.b) ); p.drawText(0,r.height() - fm.descent() -1 , text_); p.end(); buf_ = pm_.toImage(); #else bm.fill(Qt::color0); p.begin( &bm ); p.setPen(Qt::color1); p.setFont(font_); p.drawText(0,r.height() - fm.descent() -1 , text_); p.end(); pm_.setMask(bm); // avoids uninitialized areas in some cases #if QT_VERSION < 0x040000 pm_.fill(); #endif p.begin( &pm_ ); p.setFont( font_ ); p.setPen( Qt::SolidLine ); p.setPen( GL2Qt(color.r, color.g, color.b) ); p.drawText(0,r.height() - fm.descent() -1 , text_); p.end(); #endif } #if QT_VERSION < 0x040000 buf_ = pm_.convertToImage(); #else buf_ = pm_.toImage(); #endif tex_ = QGLWidget::convertToGLFormat( buf_ ); // flipped 32bit RGBA ? }
/** \brief Creates a QImage comprising the depth map **/ QImage QKinectWrapper::createDepthImage() { // Here must mutex / run also access the data xn::SceneMetaData smd; xn::DepthMetaData dmd; g_DepthGenerator.GetMetaData(dmd); g_UserGenerator.GetUserPixels(0, smd); XnUInt16 g_nXRes = dmd.XRes(); XnUInt16 g_nYRes = dmd.YRes(); QImage image(g_nXRes,g_nYRes,QImage::Format_RGB32); const XnDepthPixel* pDepth = dmd.Data(); const XnLabel* pLabels = smd.Data(); // Compute stats /*unsigned max,min; max = pDepth[0]; min = 0; for (unsigned i=0; i<g_nYRes*g_nXRes; i++) { if(pDepth[i]>max) max = pDepth[i]; if(pDepth[i]!=0) { if(min==0) min = pDepth[i]; else if(pDepth[i]<min) min = pDepth[i]; } } printf("Depth min/max: %u %u\n",min,max);*/ for (unsigned nY=0; nY<g_nYRes; nY++) { uchar *imageptr = image.scanLine(nY); for (unsigned nX=0; nX < g_nXRes; nX++) { unsigned depth = *pDepth; unsigned label = *pLabels; unsigned maxdist=10000; if(depth>maxdist) depth=maxdist; if(depth) { depth = (maxdist-depth)*255/maxdist+1; } // depth: 0: invalid // depth: 255: closest // depth: 1: furtherst (maxdist distance) if(label) { imageptr[0] = BodyColors[label][0]*2*depth/255; imageptr[1] = BodyColors[label][1]*2*depth/255; imageptr[2] = BodyColors[label][2]*2*depth/255; imageptr[3] = 0xff; } else { // Here we could do depth*color, to show the colored depth imageptr[0] = depth; imageptr[1] = depth; imageptr[2] = depth; imageptr[3] = 0xff; } pDepth++; imageptr+=4; pLabels++; } } QPainter painter; painter.begin(&image); if(displayInfoDepth) { painter.setPen(textPen); painter.setFont(font); drawInfo(&painter); } if(displaySkeletonDepth) { painter.setPen(skeletonPen); drawSkeleton(&painter); } painter.end(); return image; }
void MapCanvas::paintEvent( QPaintEvent * ) { QPainter pcanvas; LocationDialog *ld = (LocationDialog *)topLevelWidget(); KStars *ks = (KStars *)ld->parent(); //prepare the canvas pcanvas.begin( Canvas ); // pcanvas.fillRect( 0, 0, width(), height(), QBrush( QColor( BGColor ) ) ); pcanvas.drawPixmap( 0, 0, *bgImage ); // pcanvas.setBrush( white ); pcanvas.setPen( QPen( QColor( "SlateGrey" ) ) ); //Draw cities QPoint o; for ( GeoLocation *g=ks->data()->geoList.first(); g; g = ks->data()->geoList.next() ) { o.setX( int( g->lng()->Degrees() + origin.x() ) ); o.setY( height() - int( g->lat()->Degrees() + origin.y() ) ); if ( o.x() >= 0 && o.x() <= width() && o.y() >=0 && o.y() <=height() ) { pcanvas.drawPoint( o.x(), o.y() ); } } //redraw the cities that appear in the filtered list, with a white pen //If the list has not been filtered, skip the redraw. if ( ld->filteredList()->count() ) { pcanvas.setPen( white ); for ( GeoLocation *g=ld->filteredList()->first(); g; g = ld->filteredList()->next() ) { o.setX( int( g->lng()->Degrees() + origin.x() ) ); o.setY( height() - int( g->lat()->Degrees() + origin.y() ) ); if ( o.x() >= 0 && o.x() <= width() && o.y() >=0 && o.y() <=height() ) { pcanvas.drawPoint( o.x(), o.y() ); } } } GeoLocation *g = ld->selectedCity(); if ( g ) { o.setX( int( g->lng()->Degrees() + origin.x() ) ); o.setY( height() - int( g->lat()->Degrees() + origin.y() ) ); pcanvas.setPen( red ); pcanvas.setBrush( red ); pcanvas.drawEllipse( o.x()-3, o.y()-3, 6, 6 ); pcanvas.moveTo( o.x()-16, o.y() ); pcanvas.lineTo( o.x()-8, o.y() ); pcanvas.moveTo( o.x()+8, o.y() ); pcanvas.lineTo( o.x()+16, o.y() ); pcanvas.moveTo( o.x(), o.y()-16 ); pcanvas.lineTo( o.x(), o.y()-8 ); pcanvas.moveTo( o.x(), o.y()+8 ); pcanvas.lineTo( o.x(), o.y()+16 ); pcanvas.setPen( white ); pcanvas.setBrush( white ); } pcanvas.end(); bitBlt( this, 0, 0, Canvas ); }