How to use QPainter::setTransform in paint() in Qt? - c++

I have a simple QGraphicsView with text written over it.That text is wrapped under a bounding rect. I have truncated a text using QFontMetrics::elidedText.
When initially view gets loaded, it shows all truncated text properly. But when I zoom-in only few truncated text gets visible. If for few more times I zoomed-in, then some times it shows all the truncated text and some times , it never shows any truncated text.
Before truncated text code gets added, zoom-in was working properly.
widget.cpp
void widget::ZoomIn()
{
double scaleFactor = 1.1;
view->scale(scaleFactor,scaleFactor);
}
void Widget::on_textButton_clicked()
{
//logic to get string s and its co-ordinates firstPos and secondPos
Text* t = new Text() ;
QGraphicsTextItem* text = t->drawText(s,firstPos,secondPos,50,40);
scene->addItem(text);
}
Text.cpp
Text::Text(const QString &text,int left,int top,int width,int height)
: QGraphicsTextItem (text),currentString(text),
Left(left),Top(top),Width(width),Height(height)
{}
Text::Text(){}
QGraphicsTextItem *Text::drawText(QString s, int left,int top,int width,int height)
{
QGraphicsTextItem *text = new Text(s,left,top,width,height);
return text;
}
void Text::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
QFont defaultFont = QApplication::font();
QFontMetrics fm = QFontMetrics(defaultFont);
QRect rect = QRect(Left,Top,Width,Height);
QString elidedText = fm.elidedText(currentString, Qt::ElideLeft,rect.width());
QTransform trans = view->transform();
QTransform prevTrans;
painter->setTransform(trans);
painter->drawText(rect,Qt::AlignRight,elidedText);
painter->setTransform(prevTrans);
}
I understood that, in zoom-in I am changing transformation and painter is drawing on old transformation. So I have to take transformation from view and set it with painter then drawText() and then set painter transformation as previous transformation.
I did , but still problem persist.

Related

How to paint an outline when hovering over a QListWidget item?

I am trying to paint an outline around a QListWidget item when the mouse is over that item. I've subclassed QStyledItemDelegate and overrode paint to account for the QStyle::State_MouseOver case as follows:
class MyDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
MyDelegate(QObject *parent = nullptr)
: QStyledItemDelegate(parent){}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QStyledItemDelegate::paint(painter, option, index);
if(option.state & QStyle::State_MouseOver) painter->drawRect(option.rect);
}
~MyDelegate(){}
};
I then instantiate a QListWidget with some items and enable the Qt::WA_Hover attribute:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QListWidget w;
w.addItems(QStringList{"item1", "item2", "item3", "item4"});
w.setItemDelegate(new MyDelegate(&w));
w.viewport()->setAttribute(Qt::WA_Hover);
w.show();
return a.exec();
}
Unfortunately, the behaviour is not what I expected. In particular, the outline is painted when I move the mouse over an item, but when I move to another item the outline around the first item is not erased. Instead, it keeps drawing outlines around all the items I move my mouse over and eventually there is an outline around all items. Is this normal? I know that an alternative solution would be to use QStyleSheets but I'd like to understand why the current approach doesn't behave as I expected.
Here is what the widget looks like before a mouse over:
Here it is after hovering over item2:
And then after item3:
I am using Qt 5.15.1 on a MacOS 10.15.6 platform.
EDIT 1:
Based on the answer from scopchanov, to ensure the outline thickness is indeed 1px, I've changed the paint method to this:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
int outlineWidth = 1;
QPen pen;
pen.setWidth(outlineWidth);
painter->setPen(pen);
QStyledItemDelegate::paint(painter, option, index);
if(option.state & QStyle::State_MouseOver) {
int a = round(0.5*(outlineWidth - 1));
int b = round(-0.5*outlineWidth);
painter->drawRect(option.rect.adjusted(a, a, b, b));
}
}
Unfortunately, the behaviour is very similar; here is a screenshot after hovering over all items from top to bottom:
Cause
QPainter::drawRect draws a rectangle, that is slightly bigger (by exactly one pixel in height and width) than the painted area. The reason for this behavior could be seen in the way QPaintEngine draws a rectangle:
for (int i=0; i<rectCount; ++i) {
QRectF rf = rects[i];
QPointF pts[4] = { QPointF(rf.x(), rf.y()),
QPointF(rf.x() + rf.width(), rf.y()),
QPointF(rf.x() + rf.width(), rf.y() + rf.height()),
QPointF(rf.x(), rf.y() + rf.height()) };
drawPolygon(pts, 4, ConvexMode);
}
QPaintEngine draws a closed polygon, starting at the point (x, y), going to (x + width, y), then to (x + width, y + height) and finally to (x, y + height). This looks intuitive enough, but let's see what happens, if we substitute these variables with real numbers:
Say, we want to draw a 4x2 px rectangle at (0, 0). QPaintEngine would use the following coordinates: (0, 0), (4, 0), (4, 2) and (0, 2). Represented as pixels, the drawing would look like this:
So, instead of 4x2 px, we end up with a 5x3 px rectangle, i.e. indeed one pixel wider and taller.
You can further prove this by clipping the painter to option.rect before calling drawRect like this:
if (option.state & QStyle::State_MouseOver) {
painter->setClipRect(option.rect);
painter->drawRect(option.rect);
}
The result is clipped bottom and right edges of the outline (the very edges, we have expected to be within the painted area):
In any case, the part of the outline, that falls outside of the painted area, is not repainted correctly, hence the unwanted remains of the previous drawings in the form of lines.
Solution
Reduce the height and the width of the outline, using QRect::adjusted.
You might just write
painter->drawRect(option.rect.adjusted(0, 0, -1, -1));
However, this would work only for an outline, which is 1px thick and the devicePixelRatio is 1, as on a PC. If the border of the outline is thicker than 1px and/or the devicePixelRatio is 2, as on a Mac, of course more of the outline will stick out of the painted area, so you should take that into consideration and adjust the rectangle accordingly, e.g.:
int effectiveOutlineWidth = m_outineWidth*m_devicePixelRatio;
int tl = round(0.5*(effectiveOutlineWidth - 1));
int br = round(-0.5*effectiveOutlineWidth);
painter->drawRect(option.rect.adjusted(tl, tl, br, br));
m_outineWidth and m_devicePixelRatio are class members, representing the desired outline width, resp. the ratio between physical pixels and device-independent pixels for the paint device. Provided that you have created public setter methods for them, you could set their values like this:
auto *delegate = new MyDelegate(&w);
delegate->setOutlineWidth(1);
delegate->setDevicePixelRatio(w.devicePixelRatio());
w.setItemDelegate(delegate);
Example
Here is an example I have written for you to demonstrate how the proposed solution could be implemented:
#include <QApplication>
#include <QStyledItemDelegate>
#include <QListWidget>
#include <QPainter>
class MyDelegate : public QStyledItemDelegate
{
int m_outineWidth;
int m_devicePixelRatio;
public:
MyDelegate(QObject *parent = nullptr) :
QStyledItemDelegate(parent),
m_outineWidth(1),
m_devicePixelRatio(1) {
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override {
QStyledItemDelegate::paint(painter, option, index);
if (option.state & QStyle::State_MouseOver) {
int effectiveOutlineWidth = m_outineWidth*m_devicePixelRatio;
int tl = round(0.5*(effectiveOutlineWidth - 1));
int br = round(-0.5*effectiveOutlineWidth);
painter->setPen(QPen(QBrush(Qt::red), m_outineWidth, Qt::SolidLine,
Qt::SquareCap, Qt::MiterJoin));
painter->drawRect(option.rect.adjusted(tl, tl, br, br));
}
}
void setOutlineWidth(int outineWidth) {
m_outineWidth = outineWidth;
}
void setDevicePixelRatio(int devicePixelRatio) {
m_devicePixelRatio = devicePixelRatio;
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QListWidget w;
auto *delegate = new MyDelegate(&w);
delegate->setOutlineWidth(3);
delegate->setDevicePixelRatio(w.devicePixelRatio());
w.setItemDelegate(delegate);
w.addItems(QStringList{"item1", "item2", "item3", "item4"});
w.viewport()->setAttribute(Qt::WA_Hover);
w.show();
return a.exec();
}
Result
The provided example produces the following result for 3px thick outline on Windows:

Display Text On QtCharts

I am using the QtCharts class to make a line graph. I want to be able to add note/text on the graph itself. How can I do this? I found a example similar to what I want " https://doc.qt.io/qt-5/qtcharts-callout-example.html" is there a easier way?
This is my version. There may be errors
textitem.h
#pragma once
#include <QtCharts/QChartGlobal>
#include <QtWidgets/QGraphicsItem>
QT_CHARTS_BEGIN_NAMESPACE
class QChart;
class QAbstractSeries;
QT_CHARTS_END_NAMESPACE
QT_CHARTS_USE_NAMESPACE
class TextItem : public QGraphicsItem {
public:
TextItem(QString text, QPoint pos, QChart *chart, QAbstractSeries *series);
QRectF boundingRect() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
void setText(const QString &text);
void setAnchor(QPointF point);
private:
QChart *_chart;
QAbstractSeries *_series;
QString _text;
QRectF _textRect;
QPointF _anchor;
};
textitem.cpp
#include "textitem.h"
#include <QtCharts/QChart>
#include <QPainter>
#include <QRect>
TextItem::TextItem(QString text, QPoint pos, QChart *chart, QAbstractSeries *series)
: QGraphicsItem(chart), _chart(chart), _series(series), _anchor(pos) {
setText(text);
}
QRectF TextItem::boundingRect() const {
QPointF anchor = mapFromParent(_chart->mapToPosition(_anchor, _series));
QRectF rect;
rect.setLeft(qMin(_textRect.left(), anchor.x()));
rect.setRight(qMax(_textRect.right(), anchor.x()));
rect.setTop(qMin(_textRect.top(), anchor.y()));
rect.setBottom(qMax(_textRect.bottom(), anchor.y()));
return rect;
}
void TextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(option)
Q_UNUSED(widget)
QPointF anchor = mapFromParent(_chart->mapToPosition(_anchor, _series));
painter->drawText(anchor, _text);
}
void TextItem::setText(const QString &text) {
_text = text;
QFontMetrics metrics((QFont()));
_textRect = metrics.boundingRect(QRect(0, 0, 150, 150),
Qt::AlignLeft, _text);
_textRect.translate(5, 5);
prepareGeometryChange();
}
void TextItem::setAnchor(QPointF point) { _anchor = point; }
I know it's a late reply and not anymore relevant for you, though it might be for others:
As far as I can see, they already use a pretty easy way of doing this.
In their example, they use the QGraphicsTextItem to add text at a specific position in a chart.
Assume you have a series and want to add text to each point in this series which is visible in the chart.
Here is an (python PySide6) example of how you can do it (you can do it the same way in c++):
chart = QChart() # some chart
series = QScatterSeries() # some series which has been added to the chart
# create text items and add to chart
my_text_items = []
for i in range(series.count()):
text_item = QGraphicsTextItem("point with idx: {}".format(i), parent=chart)
my_text_items.append(text_item)
# define function to set/update the position of the text items (has to be called during resize)
def update_position_of_text_items(text_items, series):
for i, text_item in enumerate(text_items):
# get point at index i
point = series.at(i)
# map its position of the series to the position in the chart
position_in_chart = series.chart().mapToPosition(point, series)
# set the position of the text item at index i accordingly
text_item.setPos(position_in_chart)
update_position_of_text_items(my_text_items, series)
Make sure to call the update_position_of_text_items(..) when resizing your widget.

How to keep the size and position of QGraphicsItem when scaling the view?

I have some QGraphicsItems in the QGraphicsScene which should keep the same size and position when scaling. I've tried QGraphicsItem::ItemIgnoresTransformations but it turns out that the items get wrong positions. Below is a sample code:
I have subclassed QGraphicsView like this:
class Graphics : public QGraphicsView
{
public:
Graphics();
QGraphicsScene *scene;
QGraphicsRectItem *rect;
QGraphicsRectItem *rect2;
protected:
void wheelEvent(QWheelEvent *event);
};
And in its constructor:
Graphics::Graphics()
{
scene = new QGraphicsScene;
rect = new QGraphicsRectItem(100,100,50,50);
rect2 = new QGraphicsRectItem(-100,-100,50,50);
scene->addLine(0,200,200,0);
rect->setFlag(QGraphicsItem::ItemIgnoresTransformations, true);
scene->addItem(rect);
scene->addItem(rect2);
setScene(scene);
scene->addRect(scene->itemsBoundingRect());
}
The wheelEvent virtual function:
void Graphics::wheelEvent(QWheelEvent *event)
{
if(event->delta() < 0)
scale(1.0/2.0, 1.0/2.0);
else
scale(2, 2);
scene->addRect(scene->itemsBoundingRect());
qDebug() << rect->transform();
qDebug() << rect->boundingRect();
qDebug() << rect2->transform();
qDebug() << rect2->boundingRect();
}
orginal view looks like this:
1
take the line as road and rect aside as a symbol. When zoomed out, the rect maintain its size but jumps out of the scene:
2
which should be that topleft of rect to middle of line. I'm also confused with debug info showing that the boundingRect and transform stays the same, which seems that nothing has changed! What causes the problem and is there any way to solve it? Could someone help? Thank you!
Sorry for delay, now I've solved the problem myself.
I found QGraphicsItem::ItemIgnoresTransformations only works when the point you want stick to is at (0,0) in item's coordinate. You need also update boundingRect manually in this way. Nevertheless, the best solution I've found is subclass QGraphicsItem and set matrix in paint() according to world matrix. Below is my code .
QMatrix stableMatrix(const QMatrix &matrix, const QPointF &p)
{
QMatrix newMatrix = matrix;
qreal scaleX, scaleY;
scaleX = newMatrix.m11();
scaleY = newMatrix.m22();
newMatrix.scale(1.0/scaleX, 1.0/scaleY);
qreal offsetX, offsetY;
offsetX = p.x()*(scaleX-1.0);
offsetY = p.y()*(scaleY-1.0);
newMatrix.translate(offsetX, offsetY);
return newMatrix;
}
And the paint function:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
QPointF p(left, top);
painter->setMatrix(stableMatrix(painter->worldMatrix(), p));
painter->drawRect(left, top, width, height);
}
The second argument of stableMatrix is sticked point, in my sample code it's top-left of the item. You can change it to your preference. It works really fine!
Hope this post help :)
The solution to this is even simpler.
QGraphicsItem::ItemIgnoresTransformations
The item ignores inherited transformations (i.e., its position is still anchored to its parent, but the parent or view rotation, zoom or shear transformations are ignored). [...]
And that's the key! Item ignores all transformations, but is still bound to its parent. So you need two items: a parent item that will keep the relative position (without any flags set) and a child item that will do the drawing (with QGraphicsItem::ItemIgnoresTransformations flag set) at parent's (0,0) point.
Here is some working code of a crosshair that have constant size and rotation, while keeping the relative position to its parent:
#include <QGraphicsItem>
#include <QPainter>
class CrossHair : public QGraphicsItem
{
private:
class CrossHairImpl : public QGraphicsItem
{
public:
CrossHairImpl (qreal len, QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent), m_len(len)
{
setFlag(QGraphicsItem::ItemIgnoresTransformations);
}
QRectF boundingRect (void) const override
{
return QRectF(-m_len, -m_len, m_len*2, m_len*2);
}
void paint (QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
{
painter->setPen(QPen(Qt::red, 1));
painter->drawLine(0, -m_len, 0, m_len);
painter->drawLine(-m_len, 0, m_len, 0);
}
private:
qreal m_len;
};
public:
CrossHair (qreal x, qreal y, qreal len, QGraphicsItem *parent = nullptr)
: QGraphicsItem(parent), m_impl(len, this) // <-- IMPORTANT!!!
{
setPos(x, y);
}
QRectF boundingRect (void) const override
{
return QRectF();
}
void paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override
{
// empty
}
private:
CrossHairImpl m_impl;
};

Qt Drawing pixel by pixel zoomed

I tried to find some helps around internet, i had some codes to test but none works like i want.
I would draw with Qt something pixel by pixel.
I tried with a QImage within a QLabel with the protected event mousePressEvent it worked, but the pixels are too small to see them.
I tried to scale my Image, it's much better, but the position X, Y are not the same position of the pixels now or they're not synchronized with the pixels locations.
Here a screenshot of what i want do, if someone has an idea to recreate this...
If i can exactly done this via Qt i'll save a lots of time, just a basic drawing pixel by pixel, i created this example with Paint, Black and White format zoomed to 800%.
Thanks.
This is a solution hard-coded for a specific size - just implement relative coordinate mapping between pixmap and draw widget and you are set.
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0) : QWidget(parent), pressed(0) {
color = Qt::black;
pixmap = new QPixmap("h:/small.png");
resize(240, 240);
}
~Widget() { if (pixmap) delete pixmap; }
protected:
void paintEvent(QPaintEvent *) {
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap->scaled(240, 240));
painter.drawPixmap(0, 0, *pixmap);
}
void mousePressEvent(QMouseEvent *e) {
if (e->button() == Qt::RightButton)
color = color == Qt::black ? Qt::white : Qt::black;
else {
pressed = 1;
draw(e);
}
}
void mouseReleaseEvent(QMouseEvent *) { pressed = 0; }
void mouseMoveEvent(QMouseEvent *e) { draw(e); }
private:
void draw(QMouseEvent *e) {
if (pressed) {
QPainter painter(pixmap);
painter.setPen(color);
int x = e->pos().x() / 12;
int y = e->pos().y() / 12;
painter.drawPoint(x, y);
repaint();
}
}
QColor color;
QPixmap *pixmap;
bool pressed;
};

QGraphicsView and QGraphicsItem: don´t scale item when scaling the view rect

I am using Qt´s QGraphicsView - and QGraphicsItem-subclasses.
is there a way to not scale the graphical representation of the item in the view when the view rectangle is changed, e.g. when zooming in. The default behavior is that my items scale in relation to my view rectangle.
I would like to visualize 2d points which should be represented by a thin rectangle which should not scale when zooming in the view. See a typical 3d modelling software for reference where vertex points are always shown at the same size.
Thanks!
Set the QGraphicItem's flag QGraphicsItem::ItemIgnoresTransformations to true does not work for you?
I got into the same problem, and it took me a while to figure it out. This is how I solved it.
Extend a QGraphicsItem class, override paint().
Inside the paint(), reset the transformation's scaling factor to 1(which are m11 and m22), and save the m11(x scaling factor) and m22(y scaling factor) before the reset.
Then, draw like you would normally do but multiply your x with m11 and y with m22. This avoids drawing with the default transformation, but explicitly calculates the positions according to the scene's transformation.
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
QTransform t = painter->transform();
qreal m11 = t.m11(), m22 = t.m22();
painter->save(); // save painter state
painter->setTransform(QTransform(1, t.m12(), t.m13(),
t.m21(), 1, t.m23(), t.m31(),
t.m32(), t.m33()));
int x = 0, y = 0; // item's coordinates
painter->drawText(x*m11, y*m22, "Text"); // the text itself will not be scaled, but when the scene is transformed, this text will still anchor correctly
painter->restore(); // restore painter state
}
The following code block is drawing with default transformation
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
int x = 0, y = 0;
painter->drawText(x, y, "Text");
}
You can try both to see the difference. Hope this helps.
How about this:
#include <QtGui/QApplication>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsRectItem>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
QGraphicsScene scene;
scene.addText("Hello, world!");
QRect rect(50, 50, 100, 100);
QGraphicsRectItem* recti = scene.addRect(rect);
QGraphicsView view(&scene);
// Set scale for the view
view.scale(10.0, 5.0);
// Set the inverse transformation for the item
recti->setTransform(view.transform().inverted());
view.show();
return app.exec();
}
As you can see the text is scaled up but the rectangle is not. Note that this does not only prevent the scaling for the rectangle but and other transformation.
The following solution worked perfectly for me:
void MyDerivedQGraphicsItem::paint(QPainter *painter, const StyleOptionGraphicsItem *option, QWidget *widget)
{
double scaleValue = scale()/painter->transform().m11();
painter->save();
painter->scale(scaleValue, scaleValue);
painter->drawText(...);
painter->restore();
...
}
We can also multiply the scaleValue by other mesures we want to keep its size constant outside the save/restore environment.
QPointF ref(500, 500);
QPointF vector = scaleValue * QPointF(100, 100);
painter->drawLine(ref+vector, ref-vector);
I found that if I derive a new class and reimpliment the paint function I can do
void MyDerivedQGraphicsItem::paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
double scaleValue = scale();
double scaleX = painter->transform().m11();
setScale(scaleValue / scaleX);
QGraphicsSvgItem::paint(painter,option,widget);
}
This is the best way of doing it that I have found so far, but I am still tinkering around.