示例#1
0
void Stack::updateBackground(const QImage& image, const QRect& foreground)
{
	// Make sure image is correct size
	if (image.size() != (size() * devicePixelRatioF())) {
		return;
	}

	// Load background
	m_background = QPixmap::fromImage(image, Qt::AutoColor | Qt::AvoidDither);
	m_background.setDevicePixelRatio(devicePixelRatioF());

	// Determine text area size
	const int padding = m_theme.foregroundPadding();
	const QRect foreground_rect = foreground.adjusted(padding, padding, -padding, -padding);
	if (!m_resize_timer->isActive() && (foreground_rect.size() != m_foreground_size)) {
		m_foreground_size = foreground_rect.size();

		for (Document* document : m_documents) {
			document->text()->setFixedSize(m_foreground_size);
			document->centerCursor(true);
		}
	}

	update();
}
示例#2
0
// scale at which current image fills the window
void ImageViewer::updateFitWindowScale() {
    float newMinScaleX = (float) width()  * devicePixelRatioF() / mSourceSize.width();
    float newMinScaleY = (float) height() * devicePixelRatioF() / mSourceSize.height();
    if(newMinScaleX < newMinScaleY) {
        fitWindowScale = newMinScaleX;
    } else {
        fitWindowScale = newMinScaleY;
    }
}
示例#3
0
//  simple drag behavior
inline
void ImageViewer::mouseDrag(QMouseEvent *event) {
    if( drawingRect.size().width()  > width()  * devicePixelRatioF() ||
        drawingRect.size().height() > height() * devicePixelRatioF() )
    {
        mouseMoveStartPos -= event->pos();
        scroll(mouseMoveStartPos.x() * devicePixelRatioF(),
               mouseMoveStartPos.y() * devicePixelRatioF(),
               false);
        mouseMoveStartPos = event->pos();
    }
}
示例#4
0
// ##################################################
// ####################  PAINT  #####################
// ##################################################
void ImageViewer::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event)
    QPainter painter(this);
    painter.setOpacity(mOpacity);
    if(movie && smoothAnimatedImages)
        painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
    if(pixmap) {
        pixmap->setDevicePixelRatio(devicePixelRatioF());
        // maybe pre-calculate size so we wont do it in every draw?
        QRectF dpiAdjusted(drawingRect.topLeft() / devicePixelRatioF(),
                           drawingRect.size() / devicePixelRatioF());
        //qDebug() << dpiAdjusted;
        painter.drawPixmap(dpiAdjusted, *pixmap, pixmap->rect());
    }
}
示例#5
0
void ImageViewer::fitWidth() {
    if(mIsDisplaying) {
        float scale = (float)width() * devicePixelRatioF() / mSourceSize.width();
        if(!expandImage && scale > 1.0f) {
            fitNormal();
        } else {
            setScale(scale);
            centerImage();
            if(drawingRect.height() > height()*devicePixelRatioF())
                drawingRect.moveTop(0);
            update();
        }
    } else {
        centerImage();
    }
}
示例#6
0
void Stack::updateBackground()
{
	const int margin = m_layout->rowMinimumHeight(0);
	const qreal pixelratio = devicePixelRatioF();

	// Create temporary background
	const QRectF foreground = m_theme.foregroundRect(size(), margin, pixelratio);

	QImage image(size() * pixelratio, QImage::Format_ARGB32_Premultiplied);
	image.setDevicePixelRatio(pixelratio);
	image.fill(m_theme.loadColor().rgb());
	{
		QPainter painter(&image);
		QColor color = m_theme.foregroundColor();
		color.setAlpha(m_theme.foregroundOpacity() * 2.55f);
		painter.setPen(Qt::NoPen);
		painter.setBrush(color);

		if (!m_theme.roundCornersEnabled()) {
			painter.drawRect(foreground);
		} else {
			painter.setRenderHint(QPainter::Antialiasing);
			painter.drawRoundedRect(foreground, m_theme.cornerRadius(), m_theme.cornerRadius());
		}
	}

	updateBackground(image, foreground.toRect());

	// Create proper background
	if (!m_resize_timer->isActive()) {
		m_theme_renderer->create(m_theme, size(), margin, pixelratio);
	}
}
示例#7
0
void ImageButton::setImage(const QString& image, const QString& path)
{
	QImageReader source(image);
	if (source.canRead()) {
		m_image = image;

		// Find scaled size
		const qreal pixelratio = devicePixelRatioF();
		const int edge = 100 * pixelratio;
		QSize size = source.size();
		if (size.width() > edge || size.height() > edge) {
			size.scale(QSize(edge, edge), Qt::KeepAspectRatio);
			source.setScaledSize(size);
		}

		// Create square icon with image centered
		QImage icon(QSize(edge, edge), QImage::Format_ARGB32_Premultiplied);
		icon.fill(Qt::transparent);
		QPainter painter(&icon);
		painter.drawImage((edge - size.width()) / 2, (edge - size.height()) / 2, source.read());
		painter.end();

		// Load icon
		icon.setDevicePixelRatio(pixelratio);
		setIcon(QPixmap::fromImage(icon, Qt::AutoColor | Qt::AvoidDither));

		m_path = (!path.isEmpty() && QImageReader(path).canRead()) ? path : QString();
		emit changed(m_path);
	} else {
		unsetImage();
	}
}
示例#8
0
QListWidgetItem* ThemeManager::addItem(const QString& id, bool is_default, const QString& name)
{
	const qreal pixelratio = devicePixelRatioF();
	QString icon = Theme::iconPath(id, is_default, pixelratio);
	if (!QFile::exists(icon) || QImageReader(icon).size() != (QSize(258, 153) * pixelratio)) {
		Theme theme(id, is_default);

		// Find load color in separate thread
		QFuture<QColor> load_color;
		if (!theme.isDefault() && (theme.loadColor() == theme.backgroundColor())) {
			load_color = theme.calculateLoadColor();
		}

		// Generate preview
		QRect foreground;
		QImage background = theme.render(QSize(1920, 1080), foreground, 0, pixelratio);
		QImage icon;
		theme.renderText(background, foreground, pixelratio, nullptr, &icon);
		icon.save(Theme::iconPath(theme.id(), theme.isDefault(), pixelratio));

		// Save load color
		load_color.waitForFinished();
		if (load_color.resultCount()) {
			theme.setLoadColor(load_color);
			theme.saveChanges();
		}

		QApplication::processEvents();
	}

	QListWidgetItem* item = new ThemeItem(QIcon(icon), name, is_default ? m_default_themes : m_themes);
	item->setToolTip(name);
	item->setData(Qt::UserRole, id);
	return item;
}
UpdateNotifier::UpdateNotifier(QWidget *parent)
    : QFrame(parent),
      m_icon(new QLabel),
      m_title(new NormalLabel(tr("Updates"))),
      m_content(new TipsLabel(tr("Updates detected, click to view"))),
      m_closeButton(new DImageButton(this)),
      m_settings(new QSettings("deepin", "dcc-update-notifier")),
      m_updaterInter(new com::deepin::lastore::Updater("com.deepin.lastore",
                                                       "/com/deepin/lastore",
                                                       QDBusConnection::systemBus(), this))
{
    setFixedHeight(80);
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);

    m_content->setWordWrap(true);
    m_content->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    const qreal ratio = devicePixelRatioF();
    QIcon icon = QIcon::fromTheme("system-updated", QIcon::fromTheme("application-default-icon"));
    m_icon->setFixedSize(48, 48);

    QPixmap pixmap = icon.pixmap(m_icon->width() * ratio, m_icon->height() * ratio);
    pixmap = pixmap.scaled(m_icon->width() * ratio, m_icon->height() * ratio,
                           Qt::KeepAspectRatioByExpanding,
                           Qt::SmoothTransformation);
    pixmap.setDevicePixelRatio(ratio);

    m_icon->setPixmap(pixmap);

    m_closeButton->setFixedSize(14, 14);

    m_closeButton->setObjectName("NotifyCloseButton");
    m_closeButton->setVisible(false);

    QVBoxLayout *contentLayout = new QVBoxLayout;
    contentLayout->setSpacing(0);
    contentLayout->setMargin(0);

    contentLayout->addStretch();
    contentLayout->addWidget(m_title);
    contentLayout->addSpacing(4);
    contentLayout->addWidget(m_content);
    contentLayout->addStretch();

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(40, 0, 40, 0);
    mainLayout->addWidget(m_icon);
    mainLayout->addLayout(contentLayout);

    setLayout(mainLayout);

    m_updaterInter->setSync(false);
    updatablePkgsChanged(m_updaterInter->updatablePackages());
    connect(m_updaterInter, &com::deepin::lastore::Updater::UpdatablePackagesChanged,
            this, &UpdateNotifier::updatablePkgsChanged);

    connect(m_closeButton, &DImageButton::clicked, this, &UpdateNotifier::ignoreUpdates);
}
示例#10
0
void ImageViewer::fitWindow() {
    if(mIsDisplaying) {
        bool h = mSourceSize.height() <= height() * devicePixelRatioF();
        bool w = mSourceSize.width()  <= width()  * devicePixelRatioF();
        // source image fits entirely
        if(h && w && !expandImage) {
            fitNormal();
            return;
        } else { // doesnt fit
            setScale(expandImage?fitWindowScale:minScale);
            centerImage();
            update();
        }
    } else {
        centerImage();
    }
}
示例#11
0
void Stack::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	const qreal pixelratio = devicePixelRatioF();
	const QRectF rect(event->rect().topLeft() * pixelratio, event->rect().size() * pixelratio);
	painter.drawPixmap(event->rect(), m_background, rect);
	painter.end();
}
示例#12
0
qreal MapWindow::pixelRatio() {
#if QT_VERSION >= 0x050600
    return devicePixelRatioF();
#elif QT_VERSION >= 0x050000
    return devicePixelRatio();
#else
    return 1;
#endif
}
示例#13
0
qreal MapWindow::pixelRatio() {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    return devicePixelRatioF();
#elif (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    return devicePixelRatio();
#else
    return 1;
#endif
}
示例#14
0
Frame::Frame(QFrame *parent)
    : DBlurEffectWidget(parent),
      m_wallpaperList(new WallpaperList(this)),
      m_closeButton(new DImageButton(":/images/close_round_normal.svg",
                                 ":/images/close_round_hover.svg",
                                 ":/images/close_round_press.svg", this)),
      m_dbusAppearance(new ComDeepinDaemonAppearanceInterface(AppearanceServ,
                                                              AppearancePath,
                                                              QDBusConnection::sessionBus(),
                                                              this)),
      m_mouseArea(new DRegionMonitor(this))
{
    // 截止到dtkwidget 2.0.10版本,在多个屏幕设置不同缩放比时
    // DRegionMonitor 计算的缩放后的坐标可能是错误的
    m_mouseArea->setCoordinateType(DRegionMonitor::Original);

    setFocusPolicy(Qt::StrongFocus);
    setWindowFlags(Qt::BypassWindowManagerHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    setBlendMode(DBlurEffectWidget::BehindWindowBlend);
    setMaskColor(DBlurEffectWidget::DarkColor);

    initUI();
    initSize();

    connect(m_mouseArea, &DRegionMonitor::buttonPress, [this](const QPoint &p, const int button){
        if (button == 4) {
            m_wallpaperList->prevPage();
        } else if (button == 5) {
            m_wallpaperList->nextPage();
        } else {
            qDebug() << "button pressed on blank area, quit.";

            qreal scale = devicePixelRatioF();
            const QRect sRect = this->windowHandle()->screen()->geometry();
            QRect nativeRect = geometry();

            // 获取窗口真实的geometry
            nativeRect.moveTopLeft((nativeRect.topLeft() - sRect.topLeft()) * scale + sRect.topLeft());
            nativeRect.setSize(nativeRect.size() * scale);

            if (!nativeRect.contains(p)) {
                hide();
            }
        }
    });

    m_closeButton->hide();
    connect(m_wallpaperList, &WallpaperList::mouseOverItemChanged,
            this, &Frame::handleNeedCloseButton);
    connect(m_wallpaperList, &WallpaperList::itemPressed,
            this, &Frame::onItemPressed);

    QTimer::singleShot(0, this, &Frame::initListView);
}
示例#15
0
//  Right button zooming / dragging logic
//  mouseMoveStartPos: stores the previous mouseMoveEvent() position,
//                     used to calculate delta.
//  mousePressPos: used to filter out accidental zoom events
//  mouseInteraction: tracks which action we are performing since the last mousePressEvent()
//
void ImageViewer::mousePressEvent(QMouseEvent *event) {
    QWidget::mousePressEvent(event);
    if(!mIsDisplaying)
        return;
    mouseMoveStartPos = event->pos();
    mousePressPos = mouseMoveStartPos;
    if(event->button() == Qt::RightButton) {
        setZoomPoint(event->pos() * devicePixelRatioF());
    }
}
示例#16
0
QListWidgetItem* NewGameTab::createItem(const QString& image, const QSettings& details)
{
	const qreal pixelratio = devicePixelRatioF();
	QListWidgetItem* item = ThumbnailLoader::createItem(Path::image(image), details.value(image + "/Name", tr("Untitled")).toString(), m_images, pixelratio);
	item->setData(ImageRole, image);
	item->setData(NameRole, item->text());
	item->setData(TagsRole, m_image_tags->tags(image));
	updateToolTip(item);
	return item;
}
示例#17
0
void ImageViewer::fitNormal() {
    if(!mIsDisplaying) {
        return;
    }
    setScale(1.0);
    centerImage();
    if(drawingRect.height() > height() * devicePixelRatioF()) {
        drawingRect.moveTop(0);
    }
    update();
}
void MonitorSettingDialog::onMonitorRectChanged()
{
    if (!m_monitor)
        return;

    const qreal ratio = devicePixelRatioF();
    const QRect r(m_monitor->rect().topLeft(),
                  m_monitor->rect().size() / ratio);

    DAbstractDialog::move(r.center() - rect().center());
}
示例#19
0
void ImageButton::unsetImage()
{
	m_image.clear();
	m_path.clear();

	const qreal pixelratio = devicePixelRatioF();
	QPixmap icon(QSize(100, 100) * pixelratio);
	icon.setDevicePixelRatio(pixelratio);
	icon.fill(Qt::transparent);
	setIcon(icon);

	emit changed(m_path);
}
void RefineSearchButton::paintEvent(QPaintEvent *) {
    QColor backgroundColor = palette().windowText().color();
    backgroundColor.setAlpha(hovered ? 192 : 170);

    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing, true);
    painter.setPen(Qt::NoPen);
    painter.setBrush(backgroundColor);
    painter.drawEllipse(QPoint(width(), height()), width() - 2, height() - 2);

    QPixmap pixmap =
            IconUtils::iconPixmap("refine-search", 24, backgroundColor, devicePixelRatioF());
    int pw = pixmap.width() / pixmap.devicePixelRatio();
    int ph = pixmap.height() / pixmap.devicePixelRatio();
    painter.drawPixmap(width() - pw - 6, height() - ph - 6, pw, ph, pixmap);
}
示例#21
0
//  Okular-like cursor drag behavior.
//  TODO: looks like it's broken when you have multiple screens with
//        different resolution (height in particular).
//
//  ...it is probably a bad idea to fiddle with this
inline
void ImageViewer::mouseDragWrapping(QMouseEvent *event) {
    if( drawingRect.size().width()  > width()  * devicePixelRatioF() ||
        drawingRect.size().height() > height() * devicePixelRatioF() )
    {
        bool wrapped = false;
        QPoint newPos = mapToGlobal(event->pos()); //global
        QPoint delta = mouseMoveStartPos - event->pos(); // relative
        if(delta.x() && abs(delta.x()) < desktopSize.width() / 2) {
            int left = drawingRect.x() - delta.x();
            int right = left + drawingRect.width();
            if(left <= 0 && right > width() * devicePixelRatioF()) {
                // wrap mouse along the X axis
                if(left+1 <= 0 && right-1 > width() * devicePixelRatioF()) {
                    if(newPos.x() >= desktopSize.width() - 1) {
                        newPos.setX(2);
                        cursor().setPos(newPos);
                        wrapped = true;
                    } else if(newPos.x() <= 0) {
                        newPos.setX(desktopSize.width() - 2);
                        cursor().setPos(newPos);
                        wrapped = true;
                    }
                }
                // move image
                drawingRect.moveLeft(left);
            }
        }
        if(delta.y() && abs(delta.y()) < desktopSize.height() / 2) {
            int top = drawingRect.y() - delta.y();
            int bottom = top + drawingRect.height();
            if(top <= 0 && bottom > height() * devicePixelRatioF()) {
                // wrap mouse along the Y axis
                if(top+1 <= 0 && bottom-1 > height() * devicePixelRatioF()) {
                    if(newPos.y() >= desktopSize.height() - 1) {
                        newPos.setY(2);
                        cursor().setPos(newPos);
                        wrapped = true;
                    } else if(newPos.y() <= 0) {
                        newPos.setY(desktopSize.height() - 2);
                        cursor().setPos(newPos);
                        wrapped = true;
                    }
                }
                // move image
                drawingRect.moveTop(top);
            }
        }
        if(wrapped)
            mouseMoveStartPos = mapFromGlobal(newPos);
        else
            mouseMoveStartPos = event->pos();
        update();
    }
}
示例#22
0
void ThemeManager::editTheme()
{
	QListWidgetItem* item = m_themes->currentItem();
	if (!item) {
		return;
	}

	Theme theme(item->data(Qt::UserRole).toString(), false);
	ThemeDialog dialog(theme, this);
	if (dialog.exec() == QDialog::Rejected) {
		return;
	}

	item->setText(theme.name());
	item->setIcon(QIcon(Theme::iconPath(theme.id(), false, devicePixelRatioF())));
	emit themeSelected(theme);
}
示例#23
0
QSize VideoWidget::physicalSize() const
{
#ifdef QT5_HAS_X11
    if ( QX11Info::isPlatformX11() )
    {
        Display *p_x_display = QX11Info::display();
        Window x_window = stable->winId();
        XWindowAttributes x_attributes;

        XGetWindowAttributes( p_x_display, x_window, &x_attributes );

        return QSize( x_attributes.width, x_attributes.height );
    }
#endif
#if defined(_WIN32) && HAS_QT5
    HWND hwnd;
    RECT rect;

    QWindow *window = windowHandle();
    hwnd = static_cast<HWND>(QGuiApplication::platformNativeInterface()->nativeResourceForWindow("handle", window));

    GetClientRect(hwnd, &rect);

    return QSize( rect.right, rect.bottom );
#endif

    QSize current_size = size();

#   if HAS_QT56
    /* Android-like scaling */
    current_size *= devicePixelRatioF();
#   elif HAS_QT54
    /* OSX-like scaling */
    current_size *= devicePixelRatio();
#   else
#       warning "No HiDPI support"
#   endif

    return current_size;
}
示例#24
0
void Frame::hideEvent(QHideEvent *event)
{
    DBlurEffectWidget::hideEvent(event);

    if (m_dbusDeepinWM)
        m_dbusDeepinWM->CancelHideWindows();
    m_mouseArea->unregisterRegion();

    if (m_mode == WallpaperMode) {
        if (!m_desktopWallpaper.isEmpty())
            m_dbusAppearance->Set("background", m_desktopWallpaper);
        else if (m_dbusDeepinWM)
            m_dbusDeepinWM->SetTransientBackground("");

        if (!m_lockWallpaper.isEmpty())
            m_dbusAppearance->Set("greeterbackground", m_lockWallpaper);

        ThumbnailManager *manager = ThumbnailManager::instance(devicePixelRatioF());
        manager->stop();
    }
#ifndef DISABLE_SCREENSAVER
    else if (m_mode == ScreenSaverMode) {
        m_dbusScreenSaver->Stop();
    }
#endif

    // 销毁资源
    if (m_dbusDeepinWM) {
        m_dbusDeepinWM->deleteLater();
        m_dbusDeepinWM = nullptr;
    }

    if (m_backgroundHelper) {
        m_backgroundHelper->deleteLater();
        m_backgroundHelper = nullptr;
    }

    emit done();
}
void UpdateItem::setAppInfo(const AppUpdateInfo &info)
{
    m_info = info;
    QFile file(m_info.m_icon);
    QPixmap pix;
    const qreal ratio = devicePixelRatioF();

    if (file.exists())
        pix = loadPixmap(m_info.m_icon).scaled(m_appIcon->size() * ratio,
                                               Qt::KeepAspectRatioByExpanding,
                                               Qt::SmoothTransformation);
    else {
        pix = QIcon::fromTheme(m_info.m_packageId, QIcon::fromTheme("application-x-desktop"))
                .pixmap(m_appIcon->size() * ratio)
                .scaled(m_appIcon->size() * ratio,
                        Qt::KeepAspectRatioByExpanding,
                        Qt::SmoothTransformation);
        pix.setDevicePixelRatio(ratio);
    }

    m_appIcon->setPixmap(pix);

    m_appName->setText(info.m_name.trimmed());
    m_appVersion->setText(info.m_avilableVersion.trimmed());

    const QString changelog = m_info.m_changelog;
    const QString elidedText = elidedChangelog();

    if (changelog != elidedText)
    {
        m_iconLayout->setContentsMargins(0, 10, 0, 0);
        m_appChangelog->setText(elidedText);
    } else {
        setMinimumHeight(60);
        m_iconLayout->setContentsMargins(0, 0, 0, 0);
        m_appChangelog->setText(changelog);
        m_details->setVisible(false);
    }
}
示例#26
0
void RangeHistogram::paintEvent(QPaintEvent *e)
{
  QPainter p(this);

  p.setRenderHint(QPainter::Antialiasing);

  const QBrush blackBrush(QColor(0, 0, 0));
  const QBrush redBrush(QColor(60, 0, 0));
  const QBrush greenBrush(QColor(0, 128, 0));
  const QBrush whiteBrush(QColor(255, 255, 255));

  QRectF r = rect();

  p.eraseRect(r);

  r = r.marginsRemoved(QMarginsF(m_Margin, m_Margin, m_Margin, m_Margin));

  p.fillRect(r, palette().brush(QPalette::Shadow));

  QMarginsF border(m_Border, m_Border, m_Border, m_Border);
  border /= devicePixelRatioF();

  r = r.marginsRemoved(border);

  p.fillRect(r, ValidRange() ? palette().brush(QPalette::Inactive, QPalette::Highlight) : redBrush);

  int whiteX = (int)(whiteDelta() * r.width());
  int blackX = (int)(blackDelta() * r.width() + 0.5);

  QRectF blackPoint(r.topLeft(), QSize(blackX, r.height()));
  QRectF whitePoint(r.left() + whiteX, r.top(), r.width() - whiteX, r.height());

  if(ValidRange())
  {
    p.setPen(QPen(palette().color(QPalette::Dark)));
    p.drawLine(blackPoint.topRight(), blackPoint.bottomRight());
    p.drawLine(whitePoint.topLeft(), whitePoint.bottomLeft());
  }

  p.fillRect(whitePoint, whiteBrush);
  p.fillRect(blackPoint, blackBrush);

  if(!ValidRange())
    return;

  if(!m_HistogramData.isEmpty())
  {
    float minx = delta(m_HistogramMin);
    float maxx = delta(m_HistogramMax);

    uint32_t maxval = 0;
    for(int i = 0; i < m_HistogramData.count(); i++)
    {
      float x = (float)i / (float)m_HistogramData.count();

      float xdelta = minx + x * (maxx - minx);

      if(xdelta >= 0.0f && xdelta <= 1.0f)
      {
        maxval = qMax(maxval, m_HistogramData[i]);
      }
    }

    if(maxval == 0)
      maxval = 1;

    for(int i = 0; i < m_HistogramData.count(); i++)
    {
      float x = (float)i / (float)m_HistogramData.count();
      float y = (float)m_HistogramData[i] / (float)maxval;

      float xdelta = minx + x * (maxx - minx);

      if(xdelta >= 0.0f && xdelta <= 1.0f)
      {
        float segwidth = qMax(r.width() * (maxx - minx) / (float)m_HistogramData.count(), 1.0);

        QRectF barRect(QPointF(r.left() + r.width() * (minx + x * (maxx - minx)),
                               r.bottom() - r.height() * y + 1),
                       QSizeF(segwidth, r.height() * y));

        p.fillRect(barRect, greenBrush);
      }
    }
  }

  QVector<QPointF> blackTriangle = {QPoint(blackPoint.right(), m_MarkerSize * 2),
                                    QPoint(blackPoint.right() + m_MarkerSize, 0),
                                    QPoint(blackPoint.right() - m_MarkerSize, 0)};

  QPainterPath blackPath;
  blackPath.addPolygon(QPolygonF(blackTriangle));
  p.fillPath(blackPath, palette().brush(QPalette::Dark));

  QVector<QPointF> whiteTriangle = {
      QPoint(whitePoint.left(), whitePoint.bottom() - m_MarkerSize * 2 + m_Margin),
      QPoint(whitePoint.left() + m_MarkerSize, whitePoint.bottom() + m_Margin),
      QPoint(whitePoint.left() - m_MarkerSize, whitePoint.bottom() + m_Margin)};

  QPainterPath whitePath;
  whitePath.addPolygon(QPolygonF(whiteTriangle));
  p.fillPath(whitePath, palette().brush(QPalette::Dark));

  blackTriangle[0] -= QPointF(0.0, 2.0) / devicePixelRatioF();
  blackTriangle[1] += QPointF(-2.0, 1.0) / devicePixelRatioF();
  blackTriangle[2] += QPointF(2.0, 1.0) / devicePixelRatioF();

  blackPath = QPainterPath();
  blackPath.addPolygon(QPolygonF(blackTriangle));

  whiteTriangle[0] += QPointF(0.0, 2.0) / devicePixelRatioF();
  whiteTriangle[1] -= QPointF(2.0, 1.0) / devicePixelRatioF();
  whiteTriangle[2] += QPointF(2.0, -1.0) / devicePixelRatioF();

  whitePath = QPainterPath();
  whitePath.addPolygon(QPolygonF(whiteTriangle));

  p.fillPath(blackPath, blackBrush);
  p.fillPath(whitePath, whiteBrush);
}
示例#27
0
bool ImageViewer::sourceImageFits() {
    return mSourceSize.width() < width() * devicePixelRatioF() && mSourceSize.height() < height() * devicePixelRatioF();
}
示例#28
0
/*!\reimp
*/
void QLabel::paintEvent(QPaintEvent *)
{
    Q_D(QLabel);
    QStyle *style = QWidget::style();
    QPainter painter(this);
    drawFrame(&painter);
    QRect cr = contentsRect();
    cr.adjust(d->margin, d->margin, -d->margin, -d->margin);
    int align = QStyle::visualAlignment(d->isTextLabel ? d->textDirection()
                                                       : layoutDirection(), QFlag(d->align));

#if QT_CONFIG(movie)
    if (d->movie) {
        if (d->scaledcontents)
            style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));
        else
            style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());
    }
    else
#endif
    if (d->isTextLabel) {
        QRectF lr = d->layoutRect().toAlignedRect();
        QStyleOption opt;
        opt.initFrom(this);
#ifndef QT_NO_STYLE_STYLESHEET
        if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) {
            cssStyle->styleSheetPalette(this, &opt, &opt.palette);
        }
#endif
        if (d->control) {
#ifndef QT_NO_SHORTCUT
            const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0);
            if (d->shortcutId != 0
                && underline != d->shortcutCursor.charFormat().fontUnderline()) {
                QTextCharFormat fmt;
                fmt.setFontUnderline(underline);
                d->shortcutCursor.mergeCharFormat(fmt);
            }
#endif
            d->ensureTextLayouted();

            QAbstractTextDocumentLayout::PaintContext context;
            // Adjust the palette
            context.palette = opt.palette;

            if (foregroundRole() != QPalette::Text && isEnabled())
                context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole()));

            painter.save();
            painter.translate(lr.topLeft());
            painter.setClipRect(lr.translated(-lr.x(), -lr.y()));
            d->control->setPalette(context.palette);
            d->control->drawContents(&painter, QRectF(), this);
            painter.restore();
        } else {
            int flags = align | (d->textDirection() == Qt::LeftToRight ? Qt::TextForceLeftToRight
                                                                       : Qt::TextForceRightToLeft);
            if (d->hasShortcut) {
                flags |= Qt::TextShowMnemonic;
                if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this))
                    flags |= Qt::TextHideMnemonic;
            }
            style->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), d->text, foregroundRole());
        }
    } else
#ifndef QT_NO_PICTURE
    if (d->picture) {
        QRect br = d->picture->boundingRect();
        int rw = br.width();
        int rh = br.height();
        if (d->scaledcontents) {
            painter.save();
            painter.translate(cr.x(), cr.y());
            painter.scale((double)cr.width()/rw, (double)cr.height()/rh);
            painter.drawPicture(-br.x(), -br.y(), *d->picture);
            painter.restore();
        } else {
            int xo = 0;
            int yo = 0;
            if (align & Qt::AlignVCenter)
                yo = (cr.height()-rh)/2;
            else if (align & Qt::AlignBottom)
                yo = cr.height()-rh;
            if (align & Qt::AlignRight)
                xo = cr.width()-rw;
            else if (align & Qt::AlignHCenter)
                xo = (cr.width()-rw)/2;
            painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);
        }
    } else
#endif
    if (d->pixmap && !d->pixmap->isNull()) {
        QPixmap pix;
        if (d->scaledcontents) {
            QSize scaledSize = cr.size() * devicePixelRatioF();
            if (!d->scaledpixmap || d->scaledpixmap->size() != scaledSize) {
                if (!d->cachedimage)
                    d->cachedimage = new QImage(d->pixmap->toImage());
                delete d->scaledpixmap;
                QImage scaledImage =
                    d->cachedimage->scaled(scaledSize,
                                           Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                d->scaledpixmap = new QPixmap(QPixmap::fromImage(scaledImage));
                d->scaledpixmap->setDevicePixelRatio(devicePixelRatioF());
            }
            pix = *d->scaledpixmap;
        } else
            pix = *d->pixmap;
        QStyleOption opt;
        opt.initFrom(this);
        if (!isEnabled())
            pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt);
        style->drawItemPixmap(&painter, cr, align, pix);
    }
}