Ufx
Ufx

Reputation: 2695

Why QFontMetrics return rect with cropped width in Windows 7?

I paint some text in subclassed menubar. And QFontMetrics return rectangle with cropped width. This happens in Windows 7. But it works as I expect in Debian with KDE. Why is it happen and how can I fix it?

enter image description here

class MainMenuBar : public QMenuBar
{
public:
    explicit MainMenuBar(QWidget *parent = 0);

protected:
    virtual void paintEvent(QPaintEvent *event);

private:
    QFont _font;
};

MainMenuBar::MainMenuBar(QWidget *parent) : QMenuBar(parent)
{
    _font = font();
}

void MainMenuBar::paintEvent(QPaintEvent *event)
{
    QMenuBar::paintEvent(event);

    QPainter painter(this);

    painter.setFont(_font);

    QRect rect = geometry();
    rect.setRight(200);
    rect.setLeft(rect.right() - QFontMetrics(_font).width("WWW")); // Cuts
    //rect.setLeft(rect.right() - QFontMetrics(font()).width("WWW")); // Doesn't cut
    painter.drawText(rect, Qt::AlignVCenter, "WWW");
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setMenuBar(new MainMenuBar(this));
    menuBar()->addAction(".");
}

Upvotes: -1

Views: 132

Answers (1)

Alexander V
Alexander V

Reputation: 8718

In a similar situation I would not restrict the text like that. Just allocate the rectangle as long as possible (better) or maybe to fit 4 W (not as good).

painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, "WWW");

And Qt::AlignRight will do the trick. No idea why the rendering is slightly different, though. If you clarify on your task then we will be able to come up with better approach.

The best practice would be not even that but QVBoxLayout for the entire window and QHBoxLayout for the upper widget with 'stretch' (here unsure whether you just want to right-align the text or make a fixed-width left stretch before it?) on the left plus QLabel added as widget (maybe with the right alignment). But you don't ask that and I can only assume that you did not try the better layout approach.

Upvotes: 0

Related Questions