I have code that draws a console onto a QMainWindow. If I use the paintEvent, everything looks beautiful. If I paint the text to a QPixmap, and then in my paintEvent copy it over, then the text looks ugly.
#include "mainwindow.hxx"
#include "./ui_mainwindow.h"
#include <QPainter>
#include <QString>
#include <QStaticText>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto f = font();
f.setPixelSize(70);
setFont(f);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent *event)
{
{
QPixmap img(width(), height());
QPainter painter(&img);
painter.setFont(font());
painter.setBrush(Qt::black);
painter.setPen(Qt::NoPen);
painter.drawRect(rect());
painter.setRenderHint(QPainter::HighQualityAntialiasing);
painter.setPen(Qt::blue);
painter.drawText(0, 80, "/// lorem ipsum dolor sit amet");
// Create a QPainter to draw on the window
QPainter painter2(this);
painter2.setRenderHint(QPainter::HighQualityAntialiasing);
painter2.drawPixmap(rect(), img);
}
{
// Create a QPainter to draw on the window
QPainter painter(this);
painter.setFont(font());
painter.setBrush(Qt::black);
painter.setPen(Qt::NoPen);
painter.setRenderHint(QPainter::HighQualityAntialiasing);
painter.setPen(Qt::blue);
painter.drawText(0, 300, "/// lorem ipsum dolor sit amet");
}
}
main.cxx
#include "mainwindow.hxx"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget"/>
</widget>
<resources/>
<connections/>
</ui>
I have enabled anti-aliasing on the QPainter, it does not make any difference.
In both cases, the same font is used (the Window's default font()). What is going on here? Notice in particular '/' looks pretty bad.
Just a couple of thoughts:
Did you try setting the QPainter::TextAntialiasing render hint?
Also, sometimes when using HDPI (high res screen), the reported window width & height are not actual pixels; you can check this with devicePixelRatio() and use the value to scale the size of your pixmap.