I am utilizing the Model View Delegate framework used by Qt for displaying lists of objects with custom 'views' or layouts.
Background:
I require showing a country flag, country name, city name and an optional 'premium' rating star in a list, which can be selected by a user.
To achieve this, I use the following components:
Model - a QStandardItemModel, see doc page, which holds all the data of the QListView and interaction concerns, doc page
Delegate - For drawing/displaying the data in a custom layout fashion, I use a QStyledItemDelegate, see doc page.
View - For the view, a simple QListView will suffice, as this is a single column list containing a collection of objects with a custom layout.
Tutorials and Help:
Using the following tutorial(s),
1. a messageviewer application showing how to implement a detailed model-delegate-view concept in accordance with,
2. the basics of a simple messaging menu system for Nokia smartphones, I have been able to create, with relative ease, the desired layout for my QListView.
Problem:
I am required to add QStandardItem items to my model, which will be added to my view. I do so, and it is confirmed by the delegate where each item is drawn by the paint override method.
However, during runtime, the QListView only displays 1 item. But I can use my up/down arrow keys to select various other items in the list.
Please see code below:
Setting up MVC(delegate):
mainwindow.h
//...
QStandardItemModel *modelServers;
ServerDelegate* serverDelegate;
//...
mainwindow.cpp
modelServers = new QStandardItemModel(0);
serverDelegate = new ServerDelegate(0);
ui->listServers->setModel(modelServers);
ui->listServers->setItemDelegate(serverDelegate);
and adding items (QStandardItem's) to list:
for (int i = 0; i < someList->length(); ++i) {
Server server = someList->value(i);
QStandardItem *item = new QStandardItem();
item->setData(server.getCountryName, item->setData(QPixmap("", "PNG"), ServerDelegate::DataRole::CountryFlag);
item->setData(server.getCountry(), ServerDelegate::DataRole::CountryText);
item->setData(server.getCity(), ServerDelegate::DataRole::CityText);
item->setData(i, ServerDelegate::ListIndex);
//...
modelServer->appendRow(item)
}
The finally the list displays the data, however the list is only populated with items, but only the first has visible text and images.
note: when scrolling down, only the top item is visible, see images below for an example.
e.g.
Initial Loaded list:
One scroll down
Selecting an item with no text/images:
Additional Code below:
ServerDelegate class handling the custom layout
ServerDelegate.h
#ifndef SERVERDELEGATE_H
#define SERVERDELEGATE_H
#include <QApplication>
#include <QtGui>
#include <QStyledItemDelegate>
#include <QtWidgets>
#include <qglobal.h>
#include "global.h"
class ServerDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
ServerDelegate(QStyledItemDelegate* parent = 0);
virtual ~ServerDelegate();
enum DataRole{
CountryText = Qt::UserRole + 100,
CityText = Qt::UserRole+101,
CountryFlag = Qt::UserRole+102,
SideIconFlag = Qt::UserRole+103,
ListIndex = Qt::UserRole+105
};
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
QFont fontCountry, fontCity;
};
#endif // SERVERDELEGATE_H
ServerDelegate.cpp
#include "serverdelegate.h"
ServerDelegate::ServerDelegate(QStyledItemDelegate *parent)
: QStyledItemDelegate(parent)
{
fontCountry = QApplication::font();
fontCountry.setBold(true);
fontCountry.setPointSize(QApplication::font().pointSize() + 3);
fontCity = QApplication::font();
fontCity.setItalic(true);
fontCity.setPointSize(QApplication::font().pointSize() - 1);
}
ServerDelegate::~ServerDelegate(){
}
QSize ServerDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const{
Q_UNUSED(index)
QSize totalCountrySize = QPixmap("","").size();
QSize totalSideIcon = QPixmap(":/res/images/premium", "PNG").size();
QFontMetrics fmCountry(fontCountry);
QFontMetrics fmCity(fontCity);
int fontHeight = (2 * 2) + (2 * 5) + fmCountry.height() + fmCity.height();
int iconHeight = (2 * 2) + (totalCountrySize.height() > totalSideIcon.height() ? totalCountrySize.height() : totalSideIcon.height());
int height = (fontHeight > iconHeight) ? fontHeight : iconHeight;
int width = option.rect.width();
QSize size = QSize(width, height);
return size;
}
void ServerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{
QStyledItemDelegate::paint(painter, option, index);
QRect rec = option.rect;
painter->save();
painter->setClipRect(rec);
QString countryText = index.data(DataRole::CountryText).toString();
QString cityText = index.data(DataRole::CityText).toString();
QPixmap countryFlag = QPixmap(qvariant_cast<QPixmap>(index.data(DataRole::CountryFlag)));
QPixmap sideIcon = qvariant_cast<QPixmap>(index.data(DataRole::SideIconFlag));
// Get a rectangle by size x, y.
// With cooridinates [0,0]; [x,0]; [x,y]; [0,y]
QRect topLine = option.rect,
bottomLine = option.rect;
// create top 'seperator' of X px's width, green in color;
topLine.setTop(0);
topLine.setLeft(0);
topLine.setRight(option.rect.width());
topLine.setBottom(2); // 1px down
painter->setPen(QColor(116, 183, 151));
painter->fillRect(topLine, QColor(116, 183, 151));
painter->drawRect(topLine);
// create bottom 'seperator' of X px's width, green in color;
bottomLine.setTop(option.rect.height() - 2);
bottomLine.setLeft(0);
bottomLine.setRight(option.rect.width());
bottomLine.setBottom(option.rect.height()); // 1px down
painter->setPen(QColor(116, 183, 151));
painter->fillRect(bottomLine, QColor(116, 183, 151));
painter->drawRect(bottomLine);
// create background rectangle
QRect content(0, topLine.bottom(), option.rect.width(), bottomLine.top());
painter->setPen(QColor(116, 183, 151));
painter->fillRect(content, QColor(116, 183, 151));
painter->drawRect(content);
// create content rectangles from content container.
QRect rectCountryFlag = content,
rectSideIcon = content;
// create country icon rectangle
QSize countryFlagSize = countryFlag.size();
int cFPos = (rectCountryFlag.height() / 2) - (countryFlagSize.height() / 2) - 8;
rectCountryFlag.setTop(cFPos);
rectCountryFlag.setBottom(content.height() - cFPos);
rectCountryFlag.setLeft(20 - 8);
rectCountryFlag.setRight(20 + 16 + countryFlagSize.width());
painter->drawPixmap(rectCountryFlag, countryFlag);
// create side icon rectangle
QSize sideIconSize = sideIcon.size();
int siPos = (rectSideIcon.height() / 2) - (sideIconSize.height() / 2) - 4;
rectSideIcon.setTop(siPos);
rectSideIcon.setBottom(content.height() - siPos);
rectSideIcon.setLeft(rec.width() - (10 + 8 + sideIconSize.width()));
rectSideIcon.setRight(rec.width() - 10);
painter->drawPixmap(rectSideIcon, sideIcon);
const QRect textContent(rectCountryFlag.right() + 5 + 20, content.top() + 5,
rectSideIcon.left() - 5, content.bottom() - 5);
// create country text rectangle
QRect rectCountryText = content,
rectCityText = content;
rectCountryText.setLeft(textContent.left());
rectCountryText.setTop(textContent.top());
rectCountryText.setRight(textContent.right());
rectCountryText.setBottom(qRound(textContent.height() * 0.6) - 5);
painter->setPen(QColor(26, 26, 26));
painter->setFont(fontCountry);
painter->drawText(rectCountryText, countryText);
// create city text rectangle
rectCityText.setLeft(textContent.left() + ( 2 * 5));
rectCityText.setTop(rectCountryText.bottom() + 5);
rectCityText.setRight(textContent.right());
rectCityText.setBottom(textContent.height());
painter->setPen(QColor(77, 77, 77));
painter->setFont(fontCity);
painter->drawText(rectCityText, cityText);
// restore painter
painter->restore();
}
Before I post my answer, a big shoutout to scopchanov for his assistance and example provided, also hinting to the fact that an offset occurs on each call to the paint, something that I was blissfully unaware of.
Problem Explained:
The offset values provided by option.rect is the same QSize which is returned by the sizeHint method. In my case, my concern was with the y offset which had a value of 56.
My Understanding
Using the concept of the iterative offset value, I modified my code (which had previously the desired output), where I assumed that the paint method was drawn from an origin of [0,0], where infact I had to account for the offset aswel, i.e. I was not provided with a container which was placed at the next QListView item's location, instead I was given the location of the next QListView's item start point, and am required to build the item from there.
The solution:
In my case, I had the desired item layout, but items were drawn ontop of each other, due to the [0,0] origin, causing the single item effect. After changing a few values, and building a dependency hierachy of sorts, I was presented with a list of items having the desired layout.
The Code
Updated ServerDelegate.cpp
#include "serverdelegate.h"
ServerDelegate::ServerDelegate(QStyledItemDelegate *parent)
: QStyledItemDelegate(parent)
{
fontCountry = QApplication::font();
fontCountry.setBold(true);
fontCountry.setPointSize(QApplication::font().pointSize() + 3);
fontCity = QApplication::font();
fontCity.setItalic(true);
fontCity.setPointSize(QApplication::font().pointSize() - 1);
}
ServerDelegate::~ServerDelegate(){
}
QSize ServerDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const{
Q_UNUSED(index)
QSize totalCountrySize = Global::getCountryFlagFromCache(index.data(DataRole::CountryText).toString()).size();
QSize totalSideIcon = QPixmap(":/res/images/premium", "PNG").size();
QFontMetrics fmCountry(fontCountry);
QFontMetrics fmCity(fontCity);
int fontHeight = (2 * AppGlobal::Style_List_Seperator_Width) + (2 * AppGlobal::Style_List_Text_Item_Margin) + fmCountry.height() + fmCity.height();
int iconHeight = (2 * AppGlobal::Style_List_Seperator_Width) + (totalCountrySize.height() > totalSideIcon.height() ? totalCountrySize.height() : totalSideIcon.height());
int height = (fontHeight > iconHeight) ? fontHeight : iconHeight;
int width = option.rect.width();
QSize size = QSize(width, height);
return size;
}
void ServerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{
QStyledItemDelegate::paint(painter, option, index);
QFontMetrics fmCountry(fontCountry);
QFontMetrics fmCity(fontCity);
QRect rec = option.rect;
painter->save();
painter->setClipRect(rec);
QString countryText = index.data(DataRole::CountryText).toString();
QString cityText = index.data(DataRole::CityText).toString();
QPixmap countryFlag = QPixmap(qvariant_cast<QPixmap>(index.data(DataRole::CountryFlag)));
QPixmap sideIcon = qvariant_cast<QPixmap>(index.data(DataRole::SideIconFlag));
// Get a rectangle by size x, y.
// With cooridinates [0,0]; [x,0]; [x,y]; [0,y]
QRect topLine = option.rect,
bottomLine = option.rect;
// create top 'seperator' of X px's width, green in color;
topLine.setTop(rec.top());
topLine.setLeft(rec.left());
topLine.setRight(rec.right());
topLine.setBottom(rec.top() + AppGlobal::Style_List_Seperator_Width); // 1px down
painter->setPen(AppGlobal::Style_List_Seperator_Color);
painter->fillRect(topLine, AppGlobal::Style_List_Seperator_Color);
painter->drawRect(topLine);
// create bottom 'seperator' of X px's width, green in color;
bottomLine.setTop(rec.bottom() - AppGlobal::Style_List_Seperator_Width);
bottomLine.setLeft(rec.left());
bottomLine.setRight(rec.right());
bottomLine.setBottom(rec.bottom()); // 1px down
painter->setPen(AppGlobal::Style_List_Seperator_Color);
painter->fillRect(bottomLine, AppGlobal::Style_List_Seperator_Color);
painter->drawRect(bottomLine);
// create background rectangle
QRect content(rec.left(), topLine.bottom(), (rec.right() - rec.left()), (bottomLine.top() - topLine.bottom()));
painter->setPen(AppGlobal::Style_List_Background_Color);
painter->fillRect(content, ((option.state & QStyle::State_MouseOver) ? AppGlobal::Style_List_Hover_Color : AppGlobal::Style_List_Background_Color ));
painter->drawRect(content);
// create content rectangles from content container.
QRect rectCountryFlag = content,
rectSideIcon = content;
// create country icon rectangle
QSize countryFlagSize = countryFlag.size();
int cFPos = ((rectCountryFlag.bottom() - rectCountryFlag.top()) / 2) - (countryFlagSize.height() / 2) - 8;
rectCountryFlag.setTop(rectCountryFlag.top() + cFPos);
rectCountryFlag.setBottom(content.bottom() - cFPos);
rectCountryFlag.setLeft(AppGlobal::Style_List_Left_Item_Margin - 8);
rectCountryFlag.setRight(AppGlobal::Style_List_Left_Item_Margin + 16 + countryFlagSize.width());
painter->drawPixmap(rectCountryFlag, countryFlag);
// create side icon rectangle
QSize sideIconSize = sideIcon.size();
int siPos = ((rectSideIcon.bottom() - rectSideIcon.top()) / 2) - (sideIconSize.height() / 2) - 4;
rectSideIcon.setTop(rectSideIcon.top() + siPos);
rectSideIcon.setBottom(content.bottom() - siPos);
rectSideIcon.setLeft(rec.width() - (AppGlobal::Style_List_Right_Item_Margin + 8 + sideIconSize.width()));
rectSideIcon.setRight(rec.width() - AppGlobal::Style_List_Right_Item_Margin);
painter->drawPixmap(rectSideIcon, sideIcon);
int textContentLeft = rectCountryFlag.right() + AppGlobal::Style_List_Text_Item_Margin + AppGlobal::Style_List_Left_Item_Margin,
textContentTop = content.top() + AppGlobal::Style_List_Text_Item_Margin;
const QRect textContent( textContentLeft , textContentTop,
(rectSideIcon.left() - AppGlobal::Style_List_Text_Item_Margin) - textContentLeft, (content.bottom() - AppGlobal::Style_List_Text_Item_Margin) - textContentTop);
// create country text rectangle
QRect rectCountryText = content,
rectCityText = content;
rectCountryText.setLeft(textContent.left());
rectCountryText.setTop(textContent.top());
rectCountryText.setRight(textContent.right());
rectCountryText.setBottom(textContent.top() + fmCountry.height());
painter->setPen(AppGlobal::Style_Heading_Color);
painter->setFont(fontCountry);
painter->drawText(rectCountryText, countryText);
// create city text rectangle
rectCityText.setLeft(textContent.left() + ( 2 * AppGlobal::Style_List_Text_Item_Margin));
rectCityText.setTop(rectCountryText.bottom());
rectCityText.setRight(textContent.right());
rectCityText.setBottom(textContent.bottom() + fmCity.height());
painter->setPen(AppGlobal::Style_SubText_Color);
painter->setFont(fontCity);
painter->drawText(rectCityText, cityText);
// restore painter
painter->restore();
}
The problem you describe is caused by a mistake in the reimplementation of the paint method in the custom QStyledItemDelegate. You assume (0, 0) as the origin and paint everything relative to that point. However, each item has a vertical offset, which you have to take into account by using the geometry of QStyleOption::rect instead.
Here is an example of a fancy delegate with custom drawings and animations to help you further.
Related
I want to animate the color (in time) of a QTableview cell once it's value is updated via the connected data model to attract the end-users attention that something has changed.
The idea is that the color changes in gradients of f.i. blue, starts off blue just after the value change and fades to white in about 1 ~ 2 seconds.
I guess one has to use the QStyledItemDelegate here since I use the model-view concept (http://doc.qt.io/qt-5/model-view-programming.html).
One needs a trigger for the cell's value-change for the animation to start, this can be achieved via the paint() method since it is called on a value change. One can figure out the row and column, from the index parameter that is passed to paint(), to get a hold of which cell to animate.
So far so good, you can set the color of that cell to let's say blue.
Here comes the problem; the color shall fade towards white in time steps. So I was thinking about a QTimer in the QStyledItemDelegate class and maintain a kinda bookkeeping for the cell's that are being animated (could be a simple list of countdown values that are used to calculate the blue-gradient color. The lower the value the more the gradient goes towards white, once 0 the result is white which is the default color of the cell. On each QTimer timeout() event all values not equal to 0 are lowered by 1. The QStyledItemDelegate is only connected to the row of the QTableview that I want to color-animate i.e. where the value items are displayed.
Problem I face is that:
paint() is a const method so you cannot change any class
parameters.
how to re-paint the cell color on a QTimer event
(re-paint the whole QTableview is not god-style)
I managed to get it to work but I consider it a dirty solution. What I did is maintain the bookkeeping of the color animation for each cell in the data-model. I consider it a dirty solution because the color-animation is only a visual aspect so imho it should not reside in the data-model. In this way it is also not a portable solution i.e. in another project you have to rework a lot to get it to work.
I stripped down my application to the core problem. Full code can be found here (a working application): https://github.com/fruitCoder123/animated_tableview_cell
void TableViewDelegateValueWritable::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
// Paint background
uint8_t red_gradient = calculate_color_gradient(RGB_RED_MAX, RGB_RED_MIN, red_gradient_step_size, m_step_value);
uint8_t green_gradient = calculate_color_gradient(RGB_GREEN_MAX, RGB_GREEN_MIN, green_gradient_step_size, m_step_value);
painter->fillRect(option.rect, QColor(red_gradient, green_gradient, 255));
// Paint text
QStyledItemDelegate::paint(painter, option, index);
}
uint8_t TableViewDelegateValueWritable::calculate_color_gradient(const uint8_t MAX_COLOR, const uint8_t MIN_COLOR, const uint8_t step_size, uint8_t step) const
{
uint16_t color = (step_size * (1 + MAX_COLOR_GRADIENT_STEP - step)) + MIN_COLOR;
// Handle overflow and rounding errors
if(color > MAX_COLOR || color > (MAX_COLOR-(step_size/2)))
color = MAX_COLOR;
return static_cast<uint8_t>(color);
}
void TableViewDelegateValueWritable::gradient_timer_elapsed()
{
if(m_step_value)
{
m_step_value--;
m_timer->start(GRADIENT_TIMEOUT_VALUE);
//this->paint(m_painter, m_option, m_model_index);
}
}
I spent a horrific amount of hours to find a nice solution. I started with Qt a month ago so maybe I lack knowledge. Hopefully someone can give a hint how to solve it in a nice way - encapsulated in the view and not entangled with the data-model.
For the stated problems :
paint() is declared as const, you can use a mutable variable member and modify it whenever you want. For example :
class TableViewDelegateValueWritable : public QStyledItemDelegate
{
Q_OBJECT
mutable QTableView * m_view;
public:
explicit TableViewDelegateValueWritable(QTableView * view, QObject *parent){
m_view = view;
//...
}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
//...
int nFrame m_view->getFrameOfIndex(index);
drawFrame (painter, nFrame );
m_view->setFrameOfIndex(index, ++nFrame);
//...
}
//class body
}
Repaint the whole QTableView is not a god-style but repaint only the QTableView's viewport is a good option, in the MainWindow constructor :
m_db->insert_record(QString("my_val_1"), "0");
m_db->insert_record(QString("my_val_2"), "0");
m_db->insert_record(QString("my_val_3"), "0");
QTimer * timer = new QTimer( this );
connect( timer, &QTimer::timeout, this, [this](){
ui->tableView->viewport()->repaint();
});
timer->start( TIME_RESOLUTION ); //set to 1000ms
Here is a snippet to animate a cell when it was modified, the color will be changed each 1s, the method used is to subclass QSqlTableModel to track the modified cell (via dataChanged signal) :
enum MyDataRole {
ItemModifiedRole = Qt::UserRole + 1
};
class MySqlTableModel : public QSqlTableModel {
Q_OBJECT
QMap<int, QVariant > mapTimeout;
public:
MySqlTableModel( QObject *parent = Q_NULLPTR, QSqlDatabase db = QSqlDatabase() )
:QSqlTableModel( parent, db ) {
connect( this, &QSqlTableModel::dataChanged,
this, [this]( const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles )
{
for(int i = topLeft.row(); i <= bottomRight.row(); i ++ ){
mapTimeout.insert( i , QDateTime::currentDateTime() );
}
} );
}
//this data function will be called in the delegate paint() function.
QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE
{
if( role != ItemModifiedRole )
return QSqlTableModel::data( idx, role );
QMap<int, QVariant>::const_iterator it = mapTimeout.find( idx.row() );
return it == mapTimeout.end() ? QVariant() : it.value();
}
void clearEffects() {
mapTimeout.clear();
}
};
And the delegate paint() function:
// background color manipulation
void TableViewDelegateValueWritable::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSqlTableModel * db_model = (QSqlTableModel *)index.model();
QVariant v = db_model->data( index, ItemModifiedRole );
if( !v.isNull() ){
QDateTime dt = v.toDateTime();
int nTimePassed = dt.secsTo( QDateTime::currentDateTime() );
int step_value = nTimePassed + 2;
uint8_t red_gradient = calculate_color_gradient( RGB_RED_MAX, RGB_RED_MIN, red_gradient_step_size, step_value );
uint8_t green_gradient = calculate_color_gradient( RGB_GREEN_MAX, RGB_GREEN_MIN, red_gradient_step_size, step_value );
painter->fillRect( option.rect, QColor( red_gradient, green_gradient, 255) );
}
// Paint text
QStyledItemDelegate::paint(painter, option, index);
}
You should use QSqlRecord way if possible instead of executing a sql statement. In fact, after each sql statement was executed, you call the select() function, this will reset the whole table model. Here is an example of insert/update record :
void dbase::insert_record(const QString &signal_name, const QString &value)
{
QSqlRecord r = db_model->record();
r.setValue( "signal_name", signal_name );
r.setValue( "signal_value", value );
db_model->insertRecord(-1, r );
}
void dbase::update_record(const QString &signal_name, const QString &new_value)
{
for(int row = 0; row < db_model->rowCount(); row ++ ){
QSqlRecord r = db_model->record( row );
if( r.value("signal_name").toString() == signal_name ){
r.setValue("signal_value", new_value );
db_model->setRecord( row, r );
break;
}
}
}
I have a QChartView which displays some 2D points which are representing each one a specific project I want to label each point with the project name AND NOT with it's x,y coordinates as the default behaviour
Is there any way to achieve override the function that creates or render the labels?
Why this could be difficult to achieve without changing the Qt source code
QXYSeries::setPointLabelsFormat wouldn't be of much help to you. It does indeed allow you to change the format of the labels, but the only variable part of it are the coordinates of the points.
All the drawing is done in the private part of the Qt classes. Here is the whole story:
The labels are drawn in the private part of QXYSeries (painter->drawText(position, pointLabel);):
void QXYSeriesPrivate::drawSeriesPointLabels(QPainter *painter, const QVector<QPointF> &points,
const int offset)
{
if (points.size() == 0)
return;
static const QString xPointTag(QLatin1String("#xPoint"));
static const QString yPointTag(QLatin1String("#yPoint"));
const int labelOffset = offset + 2;
painter->setFont(m_pointLabelsFont);
painter->setPen(QPen(m_pointLabelsColor));
QFontMetrics fm(painter->font());
// m_points is used for the label here as it has the series point information
// points variable passed is used for positioning because it has the coordinates
const int pointCount = qMin(points.size(), m_points.size());
for (int i(0); i < pointCount; i++) {
QString pointLabel = m_pointLabelsFormat;
pointLabel.replace(xPointTag, presenter()->numberToString(m_points.at(i).x()));
pointLabel.replace(yPointTag, presenter()->numberToString(m_points.at(i).y()));
// Position text in relation to the point
int pointLabelWidth = fm.width(pointLabel);
QPointF position(points.at(i));
position.setX(position.x() - pointLabelWidth / 2);
position.setY(position.y() - labelOffset);
painter->drawText(position, pointLabel);
}
}
drawSeriesPointLabels is called from the paint method of ScatterChartItem (this class is not included in the official documentation):
void ScatterChartItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
if (m_series->useOpenGL())
return;
QRectF clipRect = QRectF(QPointF(0, 0), domain()->size());
painter->save();
painter->setClipRect(clipRect);
if (m_pointLabelsVisible) {
if (m_pointLabelsClipping)
painter->setClipping(true);
else
painter->setClipping(false);
m_series->d_func()->drawSeriesPointLabels(painter, m_points,
m_series->markerSize() / 2
+ m_series->pen().width());
}
painter->restore();
}
The ScatterChartItem in turn is created in the private part of QScatterSeries and can't be substituted with a custom class:
void QScatterSeriesPrivate::initializeGraphics(QGraphicsItem* parent)
{
Q_Q(QScatterSeries);
ScatterChartItem *scatter = new ScatterChartItem(q,parent);
m_item.reset(scatter);
QAbstractSeriesPrivate::initializeGraphics(parent);
}
What you might wanna try
Hide the original labels with setPointLabelsVisible(false); The labels will be drawn separately afterwards.
Subclass QChartView and reimplement the paintEvent, invoking first QChartView::paintEvent and then calling a custom function (lets say drawCustomLabels), which is a modified version of QXYSeriesPrivate::drawSeriesPointLabels. By calling drawCustomLabels pass:
a local painter drawing on the vieport of MyChartView,
the points as returned by QXYSeries::points,
the desired offset.
Here is an example of how the drawCustomLabels might look like:
void MyChartView::drawCustomLabels(QPainter *painter, const QVector<QPointF> &points, const int offset)
{
if (points.count() == 0)
return;
QFontMetrics fm(painter->font());
const int labelOffset = offset + 2;
painter->setFont(m_pointLabelsFont); // Use QXYSeries::pointLabelsFont() to access m_pointLabelsFont
painter->setPen(QPen(m_pointLabelsColor)); // Use QXYSeries::pointLabelsColor() to access m_pointLabelsColor
for (int n(0); n < points.count(); n++) {
QString pointLabel = "..."; // Set the desired label for the n-th point of the series
// Position text in relation to the point
int pointLabelWidth = fm.width(pointLabel);
QPointF position(points.at(n));
position.setX(position.x() - pointLabelWidth / 2);
position.setY(position.y() - labelOffset);
painter->drawText(position, pointLabel);
}
}
I'm making a dictionary program that displays word definitions in a 3-column QTableView subclass, as user types them, taking data from a QAbstractTableModel subclass. Something like that:
I want to add various formatting to the text, I'm using QAbstractItemView::setIndexWidget to add a QLabel to each cell as data comes in:
WordView.h
#include <QTableView>
class QLabel;
class WordView : public QTableView {
Q_OBJECT
public:
explicit WordView(QWidget *parent = 0);
void rowsInserted(const QModelIndex &parent, int start, int end);
private:
void insertLabels(int row);
void removeLabels(int row);
};
WordView.cpp
#include <QLabel>
#include "WordView.h"
WordView::WordView(QWidget *parent) :
QTableView(parent)
{}
void WordView::rowsInserted(const QModelIndex &parent, int start, int end) {
QTableView::rowsInserted(parent, start, end);
for (int row = start; row <= end; ++row) {
insertLabels(row);
}
}
void WordView::insertLabels(int row) {
for (int i = 0; i < 3; ++i) {
auto label = new QLabel(this);
label->setTextFormat(Qt::RichText);
label->setAutoFillBackground(true);
QModelIndex ix = model()->index(row, i);
label->setText(model()->data(ix, Qt::DisplayRole).toString()); // this has HTML
label->setWordWrap(true);
setIndexWidget(ix, label); // this calls QAbstractItemView::dataChanged
}
}
However, this is very slow - it takes around 1 second to refresh 100 rows (remove all, then add 100 new ones) like that. With original QTableView it worked fast, but I did not have formatting and ability to add links (cross-references in dictionary). How to make this much faster? Or what other widget can I use to display that data?
My requirements are:
Adding/removing around 1000 rows in ~0.2s, where around 30 will be visible at once
Clickable, multiple internal links (<a>?) in each cell (e.g. QLabel has that, QItemDelegate might have been fast, but I don't know how to get info which link I clicked there)
Formatting that allows different font sizes and colors, word wrap, different cell heights
I'm not really dead-set on QTableView, anything that looks like a scrollable table and looks consistent with Qt graphics is okay
Notes:
I tried making a single label with HTML <table> instead, but it wasn't much faster. Seems like QLabel isn't the way to go.
Data in the sample courtesy of the JMdict project.
I solved the problem by putting together few answers and looking at Qt's internals.
A solution which works very fast for static html content with links in QTableView is as folows:
Subclass QTableView and handle mouse events there;
Subclass QStyledItemDelegate and paint the html there (contrary to RazrFalcon's answer, it is very fast, as only a small amount of cells is visible at a time and only those have paint() method called);
In subclassed QStyledItemDelegate create a function that figures out which link was clicked by QAbstractTextDocumentLayout::anchorAt(). You cannot create QAbstractTextDocumentLayout yourself, but you can get it from QTextDocument::documentLayout() and, according to Qt source code, it's guaranteed to be non-null.
In subclassed QTableView modify QCursor pointer shape accordingly to whether it's hovering over a link
Below is a complete, working implementation of QTableView and QStyledItemDelegate subclasses that paint the HTML and send signals on link hover/activation. The delegate and model still have to be set outside, as follows:
wordTable->setModel(&myModel);
auto wordItemDelegate = new WordItemDelegate(this);
wordTable->setItemDelegate(wordItemDelegate); // or just choose specific columns/rows
WordView.h
class WordView : public QTableView {
Q_OBJECT
public:
explicit WordView(QWidget *parent = 0);
signals:
void linkActivated(QString link);
void linkHovered(QString link);
void linkUnhovered();
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
private:
QString anchorAt(const QPoint &pos) const;
private:
QString _mousePressAnchor;
QString _lastHoveredAnchor;
};
WordView.cpp
#include <QApplication>
#include <QCursor>
#include <QMouseEvent>
#include "WordItemDelegate.h"
#include "WordView.h"
WordView::WordView(QWidget *parent) :
QTableView(parent)
{
// needed for the hover functionality
setMouseTracking(true);
}
void WordView::mousePressEvent(QMouseEvent *event) {
QTableView::mousePressEvent(event);
auto anchor = anchorAt(event->pos());
_mousePressAnchor = anchor;
}
void WordView::mouseMoveEvent(QMouseEvent *event) {
auto anchor = anchorAt(event->pos());
if (_mousePressAnchor != anchor) {
_mousePressAnchor.clear();
}
if (_lastHoveredAnchor != anchor) {
_lastHoveredAnchor = anchor;
if (!_lastHoveredAnchor.isEmpty()) {
QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor));
emit linkHovered(_lastHoveredAnchor);
} else {
QApplication::restoreOverrideCursor();
emit linkUnhovered();
}
}
}
void WordView::mouseReleaseEvent(QMouseEvent *event) {
if (!_mousePressAnchor.isEmpty()) {
auto anchor = anchorAt(event->pos());
if (anchor == _mousePressAnchor) {
emit linkActivated(_mousePressAnchor);
}
_mousePressAnchor.clear();
}
QTableView::mouseReleaseEvent(event);
}
QString WordView::anchorAt(const QPoint &pos) const {
auto index = indexAt(pos);
if (index.isValid()) {
auto delegate = itemDelegate(index);
auto wordDelegate = qobject_cast<WordItemDelegate *>(delegate);
if (wordDelegate != 0) {
auto itemRect = visualRect(index);
auto relativeClickPosition = pos - itemRect.topLeft();
auto html = model()->data(index, Qt::DisplayRole).toString();
return wordDelegate->anchorAt(html, relativeClickPosition);
}
}
return QString();
}
WordItemDelegate.h
#include <QStyledItemDelegate>
class WordItemDelegate : public QStyledItemDelegate {
Q_OBJECT
public:
explicit WordItemDelegate(QObject *parent = 0);
QString anchorAt(QString html, const QPoint &point) const;
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
WordItemDelegate.cpp
#include <QPainter>
#include <QTextDocument>
#include <QAbstractTextDocumentLayout>
#include "WordItemDelegate.h"
WordItemDelegate::WordItemDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{}
QString WordItemDelegate::anchorAt(QString html, const QPoint &point) const {
QTextDocument doc;
doc.setHtml(html);
auto textLayout = doc.documentLayout();
Q_ASSERT(textLayout != 0);
return textLayout->anchorAt(point);
}
void WordItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
auto options = option;
initStyleOption(&options, index);
painter->save();
QTextDocument doc;
doc.setHtml(options.text);
options.text = "";
options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &option, painter);
painter->translate(options.rect.left(), options.rect.top());
QRect clip(0, 0, options.rect.width(), options.rect.height());
doc.drawContents(painter, clip);
painter->restore();
}
QSize WordItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
QStyleOptionViewItemV4 options = option;
initStyleOption(&options, index);
QTextDocument doc;
doc.setHtml(options.text);
doc.setTextWidth(options.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}
Note that this solution is fast only because a small subset of rows is rendered at once, and therefore not many QTextDocuments are rendered at once. Automatic adjusting all row heights or column widths at once will still be slow. If you need that functionality, you can make the delegate inform the view that it painted something and then making the view adjust the height/width if it hasn't before. Combine that with QAbstractItemView::rowsAboutToBeRemoved to remove cached information and you have a working solution. If you're picky about scrollbar size and position, you can compute average height based on a few sample elements in QAbstractItemView::rowsInserted and resize the rest accordingly without sizeHint.
References:
RazrFalcon's answer for pointing me to the right direction
Answer with code sample to render HTML in QTableView: How to make item view render rich (html) text in Qt
Answer with code sample on detecting links in QTreeView: Hyperlinks in QTreeView without QLabel
QLabel's and internal Qt's QWidgetTextControl's source code on how to handle mouse click/move/release for links
Many thanks for these code examples, it helped me implement similar functionalaity in my application. I'm working with Python 3 and QT5 and I would like to share my Python code, is case it may be helpful implementing this in Python.
Note that if you are using QT Designer for the UI design, you can use "promote" to change a regular "QTableView" widget to use your custom widget automatically when converting the XML to Python code with "pyuic5".
Code as follows:
from PyQt5 import QtCore, QtWidgets, QtGui
class CustomTableView(QtWidgets.QTableView):
link_activated = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
self.parent = parent
super().__init__(parent)
self.setMouseTracking(True)
self._mousePressAnchor = ''
self._lastHoveredAnchor = ''
def mousePressEvent(self, event):
anchor = self.anchorAt(event.pos())
self._mousePressAnchor = anchor
def mouseMoveEvent(self, event):
anchor = self.anchorAt(event.pos())
if self._mousePressAnchor != anchor:
self._mousePressAnchor = ''
if self._lastHoveredAnchor != anchor:
self._lastHoveredAnchor = anchor
if self._lastHoveredAnchor:
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
else:
QtWidgets.QApplication.restoreOverrideCursor()
def mouseReleaseEvent(self, event):
if self._mousePressAnchor:
anchor = self.anchorAt(event.pos())
if anchor == self._mousePressAnchor:
self.link_activated.emit(anchor)
self._mousePressAnchor = ''
def anchorAt(self, pos):
index = self.indexAt(pos)
if index.isValid():
delegate = self.itemDelegate(index)
if delegate:
itemRect = self.visualRect(index)
relativeClickPosition = pos - itemRect.topLeft()
html = self.model().data(index, QtCore.Qt.DisplayRole)
return delegate.anchorAt(html, relativeClickPosition)
return ''
class CustomDelegate(QtWidgets.QStyledItemDelegate):
def anchorAt(self, html, point):
doc = QtGui.QTextDocument()
doc.setHtml(html)
textLayout = doc.documentLayout()
return textLayout.anchorAt(point)
def paint(self, painter, option, index):
options = QtWidgets.QStyleOptionViewItem(option)
self.initStyleOption(options, index)
if options.widget:
style = options.widget.style()
else:
style = QtWidgets.QApplication.style()
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
options.text = ''
style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
textRect = style.subElementRect(QtWidgets.QStyle.SE_ItemViewItemText, options)
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
painter.translate(0, 0.5*(options.rect.height() - doc.size().height()))
doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
options = QtWidgets.QStyleOptionViewItem(option)
self.initStyleOption(options, index)
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(options.rect.width())
return QtCore.QSize(doc.idealWidth(), doc.size().height())
In your case QLabel (re)painting is slow, not QTableView.
On other hand, QTableView does not support formated text at all.
Probably, your only way, is to create your own delegate, QStyledItemDelegate, and make your own painting and click processing in it.
PS: yes, you can use QTextDocument for rendering html inside delegate, but it will be slow too.
I use a slighted improved solution based on Xilexio code. There is 3 fundamental differences:
Vertical alignment so if you put the text in a cell higher than the text it will be center aligned and not top aligned.
The text will be right shifted if the cell contains an icon so the icon will not be displayed above the text.
The widget style to highlighted cells will be followed, so you select this cell, the colors will behave similar to other cells without the delegate.
Here is my code of the paint() function (the rest of the code remains the same).
QStyleOptionViewItemV4 options = option;
initStyleOption(&options, index);
painter->save();
QTextDocument doc;
doc.setHtml(options.text);
options.text = "";
options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);
QSize iconSize = options.icon.actualSize(options.rect.size);
// right shit the icon
painter->translate(options.rect.left() + iconSize.width(), options.rect.top());
QRect clip(0, 0, options.rect.width() + iconSize.width(), options.rect.height());
painter->setClipRect(clip);
QAbstractTextDocumentLayout::PaintContext ctx;
// Adjust color palette if the cell is selected
if (option.state & QStyle::State_Selected)
ctx.palette.setColor(QPalette::Text, option.palette.color(QPalette::Active, QPalette::HighlightedText));
ctx.clip = clip;
// Vertical Center alignment instead of the default top alignment
painter->translate(0, 0.5*(options.rect.height() - doc.size().height()));
doc.documentLayout()->draw(painter, ctx);
painter->restore();
A QTreeView is rendered with the help of a custom QStyledItemDelegate::paint method. The intention is to add graphical elements to the nodes, e.g. to draw (and fill) a box around the item texts. The tree items may have check boxes, or not.
The Ruby code below achieves the goal, except that I cannot obtain the coordinates of the text element. An empirical offset (x=29; y=4) serves as a workaround. The super method draws the text on top of the box.
How can I obtain the coordinates of the text element?
Is this the right approach at all, or do I have to use drawText and drawControl instead of calling the superclass paint method? In that case, how do you control the layout of the sub elements?
(This question is not Ruby specific. Answers containing C++ are welcome.)
class ItemDelegate < Qt::StyledItemDelegate
def paint(painter, option, index)
text = index.data.toString
bg_color = Qt::Color.new(Qt::yellow)
fg_color = Qt::Color.new(Qt::black)
offset = Qt::Point.new(29,4)
painter.save
painter.translate(option.rect.topLeft + offset)
recti = Qt::Rect.new(0, 0, option.rect.width, option.rect.height)
rectf = Qt::RectF.new(recti)
margin = 4
bounding = painter.boundingRect(rectf, Qt::AlignLeft, text)
tbox = Qt::RectF.new(Qt::PointF.new(-margin,0), bounding.size)
tbox.width += 2*margin
painter.fillRect(tbox, bg_color)
painter.drawRect(tbox)
painter.restore
super
end
end
Edit: Please find a self-contained example here in this Gist.
I had the same problem in C++. Unfortunately, the workaround on option.rect.* properties seems to be the only way to find the text coords.
Here the paint method of my delegate:
void ThumbnailDelegate::paint(QPainter *p_painter, const QStyleOptionViewItem &p_option, const QModelIndex &p_index) const
{
if(p_index.isValid())
{
const QAbstractItemModel* l_model = p_index.model();
QPen l_text_pen(Qt::darkGray);
QBrush l_brush(Qt::black, Qt::SolidPattern);
/** background rect **/
QPen l_pen;
l_pen.setStyle(Qt::SolidLine);
l_pen.setWidth(4);
l_pen.setBrush(Qt::lightGray);
l_pen.setCapStyle(Qt::RoundCap);
l_pen.setJoinStyle(Qt::RoundJoin);
p_painter->setPen(l_pen);
QRect l_border_rect;
l_border_rect.setX(p_option.rect.x() + 5);
l_border_rect.setY(p_option.rect.y() + 5);
l_border_rect.setWidth(p_option.rect.width() - 16);
l_border_rect.setHeight(p_option.rect.height() - 16);
QPainterPath l_rounded_rect;
l_rounded_rect.addRect(QRectF(l_border_rect));
p_painter->setClipPath(l_rounded_rect);
/** background color for hovered items **/
p_painter->fillPath(l_rounded_rect, l_brush);
p_painter->drawPath(l_rounded_rect);
/** image **/
QPixmap l_pixmap = bytearrayToPixmap(l_model->data(p_index, ImageRole).toByteArray()).scaled(150, 150, Qt::KeepAspectRatio);
QRect l_img_rect = l_border_rect;
int l_img_x = (l_img_rect.width()/2 - l_pixmap.width()/2)+l_img_rect.x();
l_img_rect.setX(l_img_x);
l_img_rect.setY(l_img_rect.y() + 12);
l_img_rect.setWidth(l_pixmap.width());
l_img_rect.setHeight(l_pixmap.height());
p_painter->drawPixmap(l_img_rect, l_pixmap);
/** label **/
QRect l_txt_rect = p_option.rect;
l_txt_rect.setX(l_border_rect.x()+5);
l_txt_rect.setY(l_border_rect.y() + l_border_rect.height() -20);
l_txt_rect.setHeight(20);
l_txt_rect.setWidth(l_txt_rect.width()-20);
QFont l_font;
l_font.setBold(true);
l_font.setPixelSize(12);
p_painter->setFont(l_font);
p_painter->setPen(l_text_pen);
QString l_text = l_model->data(p_index, TextRole).toString();
p_painter->drawText(l_txt_rect, Qt::ElideRight|Qt::AlignHCenter, l_text);
}
else
{
qWarning() << "ThumbnailDelegate::paint() Invalid index!";
}
}
I am not skilled on Ruby but, as you can see, I am using drawPath, drawPixmap and drawText.
Here is the result:
I think it is better to avoid invoking paint from the superclass, since it should be done automatically by Qt and you may break something on the UI lifecycle.
I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space available. The screen size is not always as big as the QPixmap.
How can I modify the QSizePolicy and sizeHint() of the QLabel to resize the QPixmap while keeping the aspect ratio of the original QPixmap?
I can't modify sizeHint() of the QLabel, setting the minimumSize() to zero does not help. Setting hasScaledContents() on the QLabel allows growing, but breaks the aspect ratio thingy...
Subclassing QLabel did help, but this solution adds too much code for just a simple problem...
Any smart hints how to accomplish this without subclassing?
In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.
You can scale the pixmap by keeping its aspect ratio every time it changes:
QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();
// set a scaled pixmap to a w x h window keeping its aspect ratio
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));
There are two places where you should add this code:
When the pixmap is updated
In the resizeEvent of the widget that contains the label
I have polished this missing subclass of QLabel. It is awesome and works well.
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
#include <QResizeEvent>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(QWidget *parent = 0);
virtual int heightForWidth( int width ) const;
virtual QSize sizeHint() const;
QPixmap scaledPixmap() const;
public slots:
void setPixmap ( const QPixmap & );
void resizeEvent(QResizeEvent *);
private:
QPixmap pix;
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
//#include <QDebug>
AspectRatioPixmapLabel::AspectRatioPixmapLabel(QWidget *parent) :
QLabel(parent)
{
this->setMinimumSize(1,1);
setScaledContents(false);
}
void AspectRatioPixmapLabel::setPixmap ( const QPixmap & p)
{
pix = p;
QLabel::setPixmap(scaledPixmap());
}
int AspectRatioPixmapLabel::heightForWidth( int width ) const
{
return pix.isNull() ? this->height() : ((qreal)pix.height()*width)/pix.width();
}
QSize AspectRatioPixmapLabel::sizeHint() const
{
int w = this->width();
return QSize( w, heightForWidth(w) );
}
QPixmap AspectRatioPixmapLabel::scaledPixmap() const
{
return pix.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
void AspectRatioPixmapLabel::resizeEvent(QResizeEvent * e)
{
if(!pix.isNull())
QLabel::setPixmap(scaledPixmap());
}
Hope that helps!
(Updated resizeEvent, per #dmzl's answer)
I just use contentsMargin to fix the aspect ratio.
#pragma once
#include <QLabel>
class AspectRatioLabel : public QLabel
{
public:
explicit AspectRatioLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
~AspectRatioLabel();
public slots:
void setPixmap(const QPixmap& pm);
protected:
void resizeEvent(QResizeEvent* event) override;
private:
void updateMargins();
int pixmapWidth = 0;
int pixmapHeight = 0;
};
#include "AspectRatioLabel.h"
AspectRatioLabel::AspectRatioLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f)
{
}
AspectRatioLabel::~AspectRatioLabel()
{
}
void AspectRatioLabel::setPixmap(const QPixmap& pm)
{
pixmapWidth = pm.width();
pixmapHeight = pm.height();
updateMargins();
QLabel::setPixmap(pm);
}
void AspectRatioLabel::resizeEvent(QResizeEvent* event)
{
updateMargins();
QLabel::resizeEvent(event);
}
void AspectRatioLabel::updateMargins()
{
if (pixmapWidth <= 0 || pixmapHeight <= 0)
return;
int w = this->width();
int h = this->height();
if (w <= 0 || h <= 0)
return;
if (w * pixmapHeight > h * pixmapWidth)
{
int m = (w - (pixmapWidth * h / pixmapHeight)) / 2;
setContentsMargins(m, 0, m, 0);
}
else
{
int m = (h - (pixmapHeight * w / pixmapWidth)) / 2;
setContentsMargins(0, m, 0, m);
}
}
Works perfectly for me so far. You're welcome.
Adapted from Timmmm to PYQT5
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel
class Label(QLabel):
def __init__(self):
super(Label, self).__init__()
self.pixmap_width: int = 1
self.pixmapHeight: int = 1
def setPixmap(self, pm: QPixmap) -> None:
self.pixmap_width = pm.width()
self.pixmapHeight = pm.height()
self.updateMargins()
super(Label, self).setPixmap(pm)
def resizeEvent(self, a0: QResizeEvent) -> None:
self.updateMargins()
super(Label, self).resizeEvent(a0)
def updateMargins(self):
if self.pixmap() is None:
return
pixmapWidth = self.pixmap().width()
pixmapHeight = self.pixmap().height()
if pixmapWidth <= 0 or pixmapHeight <= 0:
return
w, h = self.width(), self.height()
if w <= 0 or h <= 0:
return
if w * pixmapHeight > h * pixmapWidth:
m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
self.setContentsMargins(m, 0, m, 0)
else:
m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
self.setContentsMargins(0, m, 0, m)
I tried using phyatt's AspectRatioPixmapLabel class, but experienced a few problems:
Sometimes my app entered an infinite loop of resize events. I traced this back to the call of QLabel::setPixmap(...) inside the resizeEvent method, because QLabel actually calls updateGeometry inside setPixmap, which may trigger resize events...
heightForWidth seemed to be ignored by the containing widget (a QScrollArea in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
I want the label to never grow more than the original pixmap size
QLabel's implementation of minimumSizeHint() does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite it
That said, here is my solution. I found that I could just use setScaledContents(true) and let QLabel handle the resizing.
Of course, this depends on the containing widget / layout honoring the heightForWidth.
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
virtual int heightForWidth(int width) const;
virtual bool hasHeightForWidth() { return true; }
virtual QSize sizeHint() const { return pixmap()->size(); }
virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
QLabel(parent)
{
QLabel::setPixmap(pixmap);
setScaledContents(true);
QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
policy.setHeightForWidth(true);
this->setSizePolicy(policy);
}
int AspectRatioPixmapLabel::heightForWidth(int width) const
{
if (width > pixmap()->width()) {
return pixmap()->height();
} else {
return ((qreal)pixmap()->height()*width)/pixmap()->width();
}
}
If your image is a resource or a file you don't need to subclass anything; just set image in the label's stylesheet; and it will be scaled to fit the label while keeping its aspect ratio, and will track any size changes made to the label. You can optionally use image-position to move the image to one of the edges.
It doesn't fit the OP's case of a dynamically updated pixmap (I mean, you can set different resources whenever you want but they still have to be resources), but it's a good method if you're using pixmaps from resources.
Stylesheet example:
image: url(:/resource/path);
image-position: right center; /* optional: default is centered. */
In code (for example):
QString stylesheet = "image:url(%1);image-position:right center;";
existingLabel->setStyleSheet(stylesheet.arg(":/resource/path"));
Or you can just set the stylesheet property right in Designer:
Icon source: Designspace Team via Flaticon
The caveat is that it won't scale the image larger, only smaller, so make sure your image is bigger than your range of sizes if you want it to grow (note that it can support SVG, which can improve quality).
The label's size can be controlled as per usual: either use size elements in the stylesheet or use the standard layout and size policy strategies.
See the documentation for details.
This style has been present since early Qt (position was added in 4.3 circa 2007 but image was around before then).
I finally got this to work as expected. It is essential to override sizeHint as well as resizeEvent, and to set the minimum size and the size policy.
setAlignment is used to centre the image in the control either horizontally or vertically when the control is a different aspect ratio to the image.
class ImageDisplayWidget(QLabel):
def __init__(self, max_enlargement=2.0):
super().__init__()
self.max_enlargement = max_enlargement
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.setAlignment(Qt.AlignCenter)
self.setMinimumSize(1, 1)
self.__image = None
def setImage(self, image):
self.__image = image
self.resize(self.sizeHint())
self.update()
def sizeHint(self):
if self.__image:
return self.__image.size() * self.max_enlargement
else:
return QSize(1, 1)
def resizeEvent(self, event):
if self.__image:
pixmap = QPixmap.fromImage(self.__image)
scaled = pixmap.scaled(event.size(), Qt.KeepAspectRatio)
self.setPixmap(scaled)
super().resizeEvent(event)
The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable.
Additionally, to resize QLabel while honoring aspect ratio use:
label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));
The width and height can be set based on scrollarea.width() and scrollarea.height().
In this way there is no need to subclass QLabel.
Nothing new here really.
I mixed the accepted reply
https://stackoverflow.com/a/8212120/11413792
and
https://stackoverflow.com/a/43936590/11413792
which uses setContentsMargins,
but just coded it a bit my own way.
/**
* #brief calcMargins Calculate the margins when a rectangle of one size is centred inside another
* #param outside - the size of the surrounding rectanle
* #param inside - the size of the surrounded rectangle
* #return the size of the four margins, as a QMargins
*/
QMargins calcMargins(QSize const outside, QSize const inside)
{
int left = (outside.width()-inside.width())/2;
int top = (outside.height()-inside.height())/2;
int right = outside.width()-(inside.width()+left);
int bottom = outside.height()-(inside.height()+top);
QMargins margins(left, top, right, bottom);
return margins;
}
A function calculates the margins required to centre one rectangle inside another. Its a pretty generic function that could be used for lots of things though I have no idea what.
Then setContentsMargins becomes easy to use with a couple of extra lines
which many people would combine into one.
QPixmap scaled = p.scaled(this->size(), Qt::KeepAspectRatio);
QMargins margins = calcMargins(this->size(), scaled.size());
this->setContentsMargins(margins);
setPixmap(scaled);
It may interest somebody ... I needed to handle mousePressEvent and to know where I am within the image.
void MyClass::mousePressEvent(QMouseEvent *ev)
{
QMargins margins = contentsMargins();
QPoint labelCoordinateClickPos = ev->pos();
QPoint pixmapCoordinateClickedPos = labelCoordinateClickPos - QPoint(margins.left(),margins.top());
... more stuff here
}
My large image was from a camera and I obtained the relative coordinates [0, 1) by dividing by the width of the pixmap and then multiplied up by the width of the original image.
This is the port of #phyatt's class to PySide2.
Apart from porting i added an additional aligment in the resizeEvent in order to make the newly resized image position properly in the available space.
from typing import Union
from PySide2.QtCore import QSize, Qt
from PySide2.QtGui import QPixmap, QResizeEvent
from PySide2.QtWidgets import QLabel, QWidget
class QResizingPixmapLabel(QLabel):
def __init__(self, parent: Union[QWidget, None] = ...):
super().__init__(parent)
self.setMinimumSize(1,1)
self.setScaledContents(False)
self._pixmap: Union[QPixmap, None] = None
def heightForWidth(self, width:int) -> int:
if self._pixmap is None:
return self.height()
else:
return self._pixmap.height() * width / self._pixmap.width()
def scaledPixmap(self) -> QPixmap:
scaled = self._pixmap.scaled(
self.size() * self.devicePixelRatioF(),
Qt.KeepAspectRatio,
Qt.SmoothTransformation
)
scaled.setDevicePixelRatio(self.devicePixelRatioF());
return scaled;
def setPixmap(self, pixmap: QPixmap) -> None:
self._pixmap = pixmap
super().setPixmap(pixmap)
def sizeHint(self) -> QSize:
width = self.width()
return QSize(width, self.heightForWidth(width))
def resizeEvent(self, event: QResizeEvent) -> None:
if self._pixmap is not None:
super().setPixmap(self.scaledPixmap())
self.setAlignment(Qt.AlignCenter)