Using QWidget::render() to draw widgets that draw other widgets (custom paintEvent) - c++

I'm using Qt and C++ to create a custom widget I call ThumbnailView, which allows for left/right scrolling of thumbnail images:
class ThumbnailView : public QWidget {
public:
virtual void paintEvent(QPaintEvent *);
private:
QList<Thumbnail*> thumbList;
};
The ThumbnailView keeps an internal list of Thumbnail objects, which are also QWidget objects:
class Thumbnail : public QWidget
{
public:
virtual void paintEvent(QPaintEvent *);
};
I embed the ThumbnailView into a PreviewPane object I created:
class PreviewPane : public QWidget {
public:
virtual void paintEvent(QPaintEvent *);
private:
ThumbnailView thumbnailView;
};
When the main application loads, I create a dock widget and add the PreviewPane:
previewPaneDock = new QDockWidget(QString("PREVIEW"), this);
previewPane = new PreviewPane;
previewPaneDock->setWidget(previewPane);
this->addDockWidget(Qt::RightDockWidgetArea, previewPaneDock, Qt::Vertical);
So the idea is this: the dock widget has its widget set to previewPane, which in turn handles custom painting via paintEvent() and all mouse events (which I have omitted here). The previewPane's paintEvent does this:
void PreviewPane::paintEvent(QPaintEvent *)
{
QPainter painter(this);
...
thumbnailView.render(&painter);
}
The render() method is inherited from QWidget; this causes ThumbnailView::paintEvent() to be called:
void ThumbnailView::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QList<Thumbnail*>::iterator itr;
int curX = 0;
for (itr = thumbList.begin(); itr != thumbList.end(); ++itr) {
curX += (*itr)->width();
if (curX < xScrollOffset) continue;
(*itr)->render(&painter, QPoint(curX - xScrollOffset - (*itr)->width(), 0));
if (curX - xScrollOffset >= this->width() ) break;
}
}
As you can see, the render() method is called again on each instance of Thumbnail.
Up to this point, there are no problems, and everything works as I expect it to. ThumbnailView allows the user to scroll left/right through a list of images (Thumbnail objects) by using a timer and kinetic scrolling using mouse flicks (or touch flicks).
I've embedded a ThumbnailView onto the PreviewPane, but the ThumbnailView isn't the only thing I want on the PreviewPane, and I want to be able to specify the origin at which the widget should start drawing--this is what I tried:
void PreviewPane::paintEvent(QPaintEvent *)
{
QPainter painter(this);
// specify a target offset of 10 pixels in y direction
thumbnailView.render(&painter, QPoint(0, 10));
}
which seems to have the same effect as this:
void PreviewPane::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.translate(0, 10);
thumbnailView.render(&painter);
}
What I am expecting to happen is that the 10 pixel y-offset that I've specified to the paint transform will be passed to ThumbnailView::paintEvent(). Instead, it seems that this 10 pixel offset is propgated to each Thumbnail object, but instead of translating the Thumbnail widget, it crops it!
I've tried printing things like painter.combinedTransform().dy() and painter.worldTransform().dy() but they are always 0. Does anyone have some insight as to what happens when painter.translate() is called, or what the targetOffset parameter does in the function QWidget::render()?

In QtWidgets, all painting is clipped. It would seem that you need to apply an offset to both the painter and the clip rectangle.

Related

Why the application crashes when QPushButton::paintEvent is followed by QPainter::fillRect?

I am implementing a round button by subclassing QPushButton and handling the paintEvent. I want to show the text set by the user and then draw a circle.
The application crashes at QPainter::fillRect after calling the QPushButton::paintEvent method. If QPushButton::paintEvent is not called it does not crash, but the button text is not shown.
Here is my code:
class CRoundAnimatingBtn : public QPushButton
{
Q_OBJECT
public:
explicit CRoundAnimatingBtn(QWidget *parent = nullptr) : QPushButton(parent) {}
protected:
void resizeEvent(QResizeEvent *) { setMask(QRegion(rect(), QRegion::Ellipse)); }
void paintEvent(QPaintEvent * e) {
QPainter painter(this);
QPointF center(width()/2, height()/2);
QRadialGradient radialGradient(center, qMin(width(), height())/2, center);
QPushButton::paintEvent(e); // Application crashes if this is called
if (isDown()) {
radialGradient.setColorAt(0.0,Qt::transparent);
radialGradient.setColorAt(0.79, Qt::transparent);
radialGradient.setColorAt(0.80, Qt::gray);
radialGradient.setColorAt(0.95, Qt::black);
radialGradient.setColorAt(0.90, Qt::gray);
radialGradient.setColorAt(0.91, Qt::transparent);
} else {
radialGradient.setColorAt(0.0,Qt::transparent);
radialGradient.setColorAt(0.84, Qt::transparent);
radialGradient.setColorAt(0.85, Qt::gray);
radialGradient.setColorAt(0.90, Qt::black);
radialGradient.setColorAt(0.95, Qt::gray);
radialGradient.setColorAt(0.96, Qt::transparent);
}
painter.fillRect(rect(), radialGradient); // Application crashes here
}
};
How to fix the crash?
Cause
You first create a painter, passing a QPaintDevice *device to the constructor of QPainter, which calls QPainter::begin:
QPainter painter(this);
Then you call the base class implementation of
paintEvent:
QPushButton::paintEvent(e);
which creates a new painter QStylePainter p on the same paint device, before you are done with the first one:
void QPushButton::paintEvent(QPaintEvent *)
{
QStylePainter p(this);
QStyleOptionButton option;
initStyleOption(&option);
p.drawControl(QStyle::CE_PushButton, option);
}
Finally, you try to draw with the first painter QPainter painter using:
painter.fillRect(rectangle, radialGradient);
Important: Such approach is not allowed, as the documentation of QPainter::begin clearly says:
Warning: A paint device can only be painted by one painter at a time.
Solution
Having this in mind, I would suggest you to avoid having two active painters at the same time by moving QPushButton::paintEvent(e); to the very beginning of CRoundAnimatingBtn::paintEvent (before everything else in this event handler).
Note: If you put QPushButton::paintEvent(e); at the very end of CRoundAnimatingBtn::paintEvent, the default implementation will overpaint your custom drawing and it would not be visible.
Example
Here is how the CRoundAnimatingBtn::paintEvent might look like:
void paintEvent(QPaintEvent * e) {
QPushButton::paintEvent(e);
QPainter painter(this);
QPointF center(width()/2, height()/2);
QRadialGradient radialGradient(center, qMin(width(), height())/2, center);
...
painter.fillRect(rect(), radialGradient);
}
The example produces the following result:
As you see, the text is shown together with your custom drawing.

Changing the QPushButton region mask in its subclass to create a RoundButton

I am trying to create a round button by subclassing and setting the region mask so that I can reuse it in my project. I know we can override paintEvent method and draw a circle to show it as a round button. But the problem with this approach is that if user clicks outside the circle (but within button rect) it will be treated as a button click. This problem we don't see when set the region mask.
I tried to set the region by calling setmask method inside resizeEvent/paintEvent. In either of case, button will be blank. I am trying to figure out the place inside the subclass to set the region mask.
RoundAnimatingButton.h ->
#include <QPushButton>
namespace Ui {
class CRoundAnimatingBtn;
}
class CRoundAnimatingBtn : public QPushButton
{
Q_OBJECT
public:
explicit CRoundAnimatingBtn(QWidget *parent = nullptr);
~CRoundAnimatingBtn();
void StartAnimation(QColor r);
void StopAnimation();
public slots:
void timerEvent(QTimerEvent *e);
private:
Ui::CRoundAnimatingBtn *ui;
bool m_Spinning;
// QWidget interface
protected:
void resizeEvent(QResizeEvent *event) override;
void paintEvent(QPaintEvent * e) override;
};
#endif // ROUNDANIMATINGBTN_H
RoundAnimatingButton.cpp
CRoundAnimatingBtn::CRoundAnimatingBtn(QWidget *parent)
: QPushButton (parent)
, ui(new Ui::CRoundAnimatingBtn)
, m_Spinning(false)
{
ui->setupUi(this);
}
CRoundAnimatingBtn::~CRoundAnimatingBtn()
{
delete ui;
}
void CRoundAnimatingBtn::paintEvent(QPaintEvent *e)
{
QPushButton::paintEvent(e);
if(m_Spinning)
{
// Animating code
}
}
void CRoundAnimatingBtn::StartAnimation(QColor r)
{
m_Spinning=true;
startTimer(5);
}
void CRoundAnimatingBtn::StopAnimation()
{
m_Spinning=false;
this->update();
}
void CRoundAnimatingBtn::timerEvent(QTimerEvent *e)
{
if(m_Spinning)
this->update();
else
killTimer(e->timerId());
}
void CRoundAnimatingBtn::DrawRing()
{
}
void CRoundAnimatingBtn::resizeEvent(QResizeEvent *event)
{
// -----------------------------------
// This code didn't work
// -----------------------------------
QRect rect = this->geometry();
QRegion region(rect, QRegion::Ellipse);
qDebug() << "PaintEvent Reound button - " << region.boundingRect().size();
this->setMask(region);
// ----------------------------------
// ------------------------------------
// This code worked
// -------------------------------------
int side = qMin(width(), height());
QRegion maskedRegion(width() / 2 - side / 2, height() / 2 - side / 2, side,
side, QRegion::Ellipse);
setMask(maskedRegion);
}
Qt doc. provides a sample for “non-rectangular” widgets – Shaped Clock Example.
(Un-)Fortunately, I remembered this not before I got my own sample running.
I started in Qt doc. with
void QWidget::setMask(const QBitmap &bitmap)
Causes only the pixels of the widget for which bitmap has a corresponding 1 bit to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform.
Note that this effect can be slow if the region is particularly complex.
The following code shows how an image with an alpha channel can be used to generate a mask for a widget:
QLabel topLevelLabel;
QPixmap pixmap(":/images/tux.png");
topLevelLabel.setPixmap(pixmap);
topLevelLabel.setMask(pixmap.mask());
The label shown by this code is masked using the image it contains, giving the appearance that an irregularly-shaped image is being drawn directly onto the screen.
Masked widgets receive mouse events only on their visible portions.
See also mask(), clearMask(), windowOpacity(), and Shaped Clock Example.
(When reading this, I still missed the link to example.)
At first, I prepared a suitable pixmap for my purpose – dialog-error.png:
for which I converted an SVG from one of my applications.
I tried to apply it to a QPushButton as icon and as mask. This looked very strange. I'm not quite sure what exactly was the problem:
- using the resp. QPushButton as toplevel widget (i.e. main window)
- the fact that QPushButtons icon rendering and the mask may not match concerning position or size.
Without digging deeper, I changed the code and fixed both issues in next try:
making a derived button (like described by OP)
using the button as non-toplevel widget.
This worked soon. I added some code to make the effect more obvious:
a mouse press event handler for main window to show whether shape is considered correctly
a signal handler to show whether clicks on button (in shape) are received correctly.
So, I came to the following sample – testQPushButtonMask.cc:
#include <QtWidgets>
class MainWindow: public QWidget {
public:
explicit MainWindow(QWidget *pQParent = nullptr):
QWidget(pQParent)
{ }
virtual ~MainWindow() = default;
MainWindow(const MainWindow&) = delete;
MainWindow& operator=(const MainWindow&) = delete;
protected:
virtual void mousePressEvent(QMouseEvent *pQEvent) override;
};
void MainWindow::mousePressEvent(QMouseEvent *pQEvent)
{
qDebug() << "MainWindow::mousePressEvent:" << pQEvent->pos();
QWidget::mousePressEvent(pQEvent);
}
class RoundButton: public QPushButton {
private:
QPixmap _qPixmap;
public:
RoundButton(const QPixmap &qPixmap, QWidget *pQParent = nullptr):
QPushButton(pQParent),
_qPixmap(qPixmap)
{
setMask(_qPixmap.mask());
}
virtual ~RoundButton() = default;
RoundButton(const RoundButton&) = delete;
RoundButton& operator=(const RoundButton&) = delete;
virtual QSize sizeHint() const override;
protected:
virtual void paintEvent(QPaintEvent *pQEvent) override;
};
QSize RoundButton::sizeHint() const { return _qPixmap.size(); }
void RoundButton::paintEvent(QPaintEvent*)
{
QPainter qPainter(this);
const int xy = isDown() * -2;
qPainter.drawPixmap(xy, xy, _qPixmap);
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
QPixmap qPixmap("./dialog-error.png");
// setup GUI
MainWindow qWin;
qWin.setWindowTitle(QString::fromUtf8("QPushButton with Mask"));
QVBoxLayout qVBox;
RoundButton qBtn(qPixmap);
qVBox.addWidget(&qBtn);
qWin.setLayout(&qVBox);
qWin.show();
// install signal handlers
QObject::connect(&qBtn, &RoundButton::clicked,
[](bool) { qDebug() << "RoundButton::clicked()"; });
// runtime loop
return app.exec();
}
The corresponding Qt project file testQPushButtonMask.pro
SOURCES = testQPushButtonMask.cc
QT += widgets
Compiled and tested on cygwin64:
$ qmake-qt5 testQPushButtonMask.pro
$ make && ./testQPushButtonMask
Qt Version: 5.9.4
MainWindow::mousePressEvent: QPoint(23,22)
MainWindow::mousePressEvent: QPoint(62,24)
MainWindow::mousePressEvent: QPoint(62,61)
MainWindow::mousePressEvent: QPoint(22,60)
RoundButton::clicked()
Concerning the output:
I clicked into the four corners of button.
I clicked on the center of button.

Translate screen drawing to another part of the screen

Is it possible to make it so that all drawing to an area "A" is translated to an area "B"?
For example drawing to the area(0,0)(100,100) and have it appear in area(200,200)(300,300).
The question is actually tagged with windows and graphics. This might have been targeted to Win32 and GDI (where I've unfortunately nearly no experience). So, the following might be seen as proof of concept:
I couldn't resist to implement the idea / concept using QWindow and QPixmap.
The concept is:
open a window fullscreen (i.e. without decoration)
make a snapshot and store it internally (in my case a )
display the internal image in window (the user cannot notice the difference)
perform a loop where pixmap is modified and re-displayed periodically (depending or not depending on user input).
And this is how I did it in Qt:
I opened a QWindow and made it fullscreen. (Maximum size may make the window full screen as well but it still will have decoration (titlebar with system menu etc.) which is unintended.)
Before painting anything, a snapshot of this window is done. That's really easy in Qt using QScreen::grabWindow(). The grabbed contents is returned as QPixmap and stored as member of my derived Window class.
The visual output just paints the stored member QPixmap.
I used a QTimer to force periodical changes of the QPixmap. To keep the sample code as short as possible, I didn't make the effort of shuffling tiles. Instead, I simply scrolled the pixmap copying a small part, moving the rest upwards, and inserting the small stripe at bottom again.
The sample code qWindowRoll.cc:
#include <QtWidgets>
class Window: public QWindow {
private:
// the Qt backing store for window
QBackingStore _qBackStore;
// background pixmap
QPixmap _qPixmap;
public:
// constructor.
Window():
QWindow(),
_qBackStore(this)
{
showFullScreen();
}
// destructor.
virtual ~Window() = default;
// disabled:
Window(const Window&) = delete;
Window& operator=(const Window&) = delete;
// do something with pixmap
void changePixmap()
{
enum { n = 4 };
if (_qPixmap.height() < n) return; // not yet initialized
const QPixmap qPixmapTmp = _qPixmap.copy(0, 0, _qPixmap.width(), n);
//_qPixmap.scroll(0, -n, 0, n, _qPixmap.width(), _qPixmap.height() - n);
{ QPainter qPainter(&_qPixmap);
qPainter.drawPixmap(
QRect(0, 0, _qPixmap.width(), _qPixmap.height() - n),
_qPixmap,
QRect(0, n, _qPixmap.width(), _qPixmap.height() - n));
qPainter.drawPixmap(0, _qPixmap.height() - n, qPixmapTmp);
}
requestUpdate();
}
protected: // overloaded events
virtual bool event(QEvent *pQEvent) override
{
if (pQEvent->type() == QEvent::UpdateRequest) {
paint();
return true;
}
return QWindow::event(pQEvent);
}
virtual void resizeEvent(QResizeEvent *pQEvent)
{
_qBackStore.resize(pQEvent->size());
paint();
}
virtual void exposeEvent(QExposeEvent*) override
{
paint();
}
// shoot screen
// inspired by http://doc.qt.io/qt-5/qtwidgets-desktop-screenshot-screenshot-cpp.html
void makeScreenShot()
{
if (QScreen *pQScr = screen()) {
_qPixmap = pQScr->grabWindow(winId());
}
}
private: // internal stuff
// paint
void paint()
{
if (!isExposed()) return;
QRect qRect(0, 0, width(), height());
if (_qPixmap.width() != width() || _qPixmap.height() != height()) {
makeScreenShot();
}
_qBackStore.beginPaint(qRect);
QPaintDevice *pQPaintDevice = _qBackStore.paintDevice();
QPainter qPainter(pQPaintDevice);
qPainter.drawPixmap(0, 0, _qPixmap);
_qBackStore.endPaint();
_qBackStore.flush(qRect);
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
// setup GUI
Window win;
win.setVisible(true);
// setup timer
QTimer qTimer;
qTimer.setInterval(50); // 50 ms -> 20 Hz (round about)
QObject::connect(&qTimer, &QTimer::timeout,
&win, &Window::changePixmap);
qTimer.start();
// run application
return app.exec();
}
I compiled and tested with Qt 5.9.2 on Windows 10. And this is how it looks:
Note: On my desktop, the scrolling is smooth. I manually made 4 snapshots and composed a GIF in GIMP – hence the image appears a bit stuttering.

Qt how to create bitmap from data from QVector and show it on widget?

I'm wondering how I can create bitmap from my data and show it on my widget.
I have QVector vector, which is vector of some points to draw chart. How I can repaint it on my widget but with using QBitmap? I don't want draw simply on widget, I prefer pass the pixmap to widget, just to show it.
How can I do this?
My code:
QPainter painter(pixMap);
painter.setPen(QPen(Qt::black, 2));
painter.drawPolyline(this->data.data(), this->data.size());
painter.drawLine(QPointF(5,5),QPointF(50,50));
setPixmap(*pixMap);
Here is my sample code. Why it's not working? I can't see anything on widget.
I have widget class
class Widget : public QLabel
{
public:
Widget(QVector<QPointF> * data);
~Widget();
protected:
void paintEvent(QPaintEvent * event);
private:
QVector<QPointF> data;
QPixmap *pixMap;
};
In constructor I have
Widget::Widget(QVector<QPointF> * data){
pixMap = new QPixmap(300,300);
pixMap->fill(Qt::red);
}
And in paintEvent
void Waveform::paintEvent(QPaintEvent *event)
{
QPainter painter(pixMap);
painter.setPen(QPen(Qt::white, 2));
painter.drawPolyline(this->data.data(), this->data.size());
painter.drawLine(QPointF(5,5),QPointF(50,50));
setPixmap(*pixMap);
}
If I replace QPainter painter(pixMap) with QPainter painter(this), I can see my chart. But I want to use pixmap.
I think so, but I wasn't sure without full code, now I am absolutely sure. You should do standard processing of paintEvent. So try this:
void Waveform::paintEvent(QPaintEvent *e)
{
static const QPointF points[3] = {
QPointF(10.0, 80.0),
QPointF(20.0, 10.0),
QPointF(80.0, 30.0),
};
QPainter painter(pixMap);
painter.setPen(QPen(Qt::black, 2));
painter.drawPolyline(points, 3);
painter.drawLine(QPointF(5,5),QPointF(50,50));
setPixmap(*pixMap);
QLabel::paintEvent(e);//standard processing
}
But I think that you don't need paintEvent at all, then you can totally remove paintEvent from your class or do
void VertLabel::paintEvent(QPaintEvent *e)
{
QLabel::paintEvent(e);//in this case you don't need paintEvent at all, remove it from cpp and header files
}
and in constructor:
pixMap = new QPixmap(300,300);
pixMap->fill(Qt::red);
this->resize(300,300);
static const QPointF points[3] = {
QPointF(10.0, 80.0),
QPointF(20.0, 10.0),
QPointF(80.0, 30.0),
};
QPainter painter(pixMap);
painter.setPen(QPen(Qt::black, 2));
painter.drawPolyline(points, 3);
painter.drawLine(QPointF(5,5),QPointF(50,50));
setPixmap(*pixMap);

Remove scroll functionality on mouse wheel QGraphics view

I have a QGraphicsView window on my widget and have just put in an event for mouse wheel which zooms in on the image.
However as soon as i zoom in scroll bars are displayed and the scroll functionality on the mouse wheel overrides the zoom function i have.
i was wondering if there is any way that i can remove scrolling all together and add a drag to move option or maybe a CTRL and mouse wheel to zoom and mouse wheel alone would control scrolling
here is my zoom function (Which im aware isnt perfect) but if anyone could shed some light on that it would be a bonus
cheers in advance
void Test::wheelEvent(QWheelEvent *event)
{
if(event->delta() > 0)
{
ui->graphicsView->scale(2,2);
}
else
{
ui->graphicsView->scale(0.5,0.5);
}
}
You reimplemented wheelEvent for QWidget/QMainWindow that contains your QGraphicsView, however, wheelEvent of QGraphicsView remains intact.
You can derive from QGraphicsView, reimplement wheelEvent for derived class and use derive class instead of QGraphicsView - this way you won't even need wheelEvent in your QWidget/QMainWindow, and you can customize reimplemented wheelEvent to do what you want. Something like that:
Header file:
class myQGraphicsView : public QGraphicsView
{
public:
myQGraphicsView(QWidget * parent = nullptr);
myQGraphicsView(QGraphicsScene * scene, QWidget * parent = nullptr);
protected:
virtual void wheelEvent(QWheelEvent * event);
};
Source file:
myQGraphicsView::myQGraphicsView(QWidget * parent)
: QGraphicsView(parent) {}
myQGraphicsView::myQGraphicsView(QGraphicsScene * scene, QWidget * parent)
: QGraphicsView(scene, parent) {}
void myQGraphicsView::wheelEvent(QWheelEvent * event)
{
// your functionality, for example:
// if ctrl pressed, use original functionality
if (event->modifiers() & Qt::ControlModifier)
{
QGraphicsView::wheelEvent(event);
}
// otherwise, do yours
else
{
if (event->delta() > 0)
{
scale(2, 2);
}
else
{
scale(0.5, 0.5);
}
}
}
Scrolling can be disabled with the following code:
ui->graphicsView->verticalScrollBar()->blockSignals(true);
ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->graphicsView->horizontalScrollBar()->blockSignals(true);
ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
I think your question has a bit simpler answer.. To disable scroll bars just set scroll bar policy (QGraphicsView is just QScrollView), so step 1)
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
that will disable scroll bars..
step 2) (if you want to keep it simple)
QGraphicsView * pView; // pointer to your graphics view
pView->setInteractive(true);
pView->setDragMode(QGraphicsView::ScrollHandDrag);
thats the fastest way to get results you want