QScrollArea自定义小部件无法正确重绘

我有一个包含我的自定义小部件的QScrollArea . 当我更改自定义窗口小部件的数据(更改sizeHint()并且窗口小部件占用更多空间)时,每行的末尾和最后几行都被截断 . 我创建了一个小程序来复制这个问题 .

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QString>

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);

    void changeData(const QString &, const unsigned &, const unsigned &);

    QSize sizeHint() const override;
protected:
    void paintEvent(QPaintEvent *event) override;

private:
    QString lines;
    unsigned lineSize = 0, rowSize = 0;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>
#include <QtWidgets>

Widget::Widget(QWidget *parent) : QWidget(parent)
{
    changeData("TESTING\nFUNCTIO\n1234567\nWORDS77\n", 7, 4);
    update();
}

void Widget::changeData(const QString &l, const unsigned &lineSz, const unsigned &rowSz)
{
    lines = l;
    lineSize = lineSz;
    rowSize = rowSz;
}

void Widget::paintEvent(QPaintEvent * /*event*/)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QFont defaultFont = painter.font();
    QPen defaultPen = painter.pen();
    defaultFont.setLetterSpacing(QFont::AbsoluteSpacing, lineSize / 2 - 3);
    // set pen and font
    painter.setFont(defaultFont);
    painter.setPen(defaultPen);
    // starting point
    QPoint prntPoint(5, 15);

    for (QString::size_type ind = 0, row = 1; ind < lines.size(); ++ind)
    {
        if (lines[ind] != '\n') // if it's a letter
        {
            // print the letter and move the point to the right
            painter.drawText(prntPoint, QString(lines[ind]));
            prntPoint.setX(prntPoint.x() + 20);
        }
        else if (lines[ind] == '\n') // if the character is a newline
        {
            prntPoint.setX(5); // move point back to the very left
            prntPoint.setY(row * 20 + 15); // move down
            ++row;
        }
    }
}

QSize Widget::sizeHint() const
{
    return QSize(lineSize * 20, rowSize * 20);
}



int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Widget *w = new Widget;
    QScrollArea area;

    area.setWidget(w);
    area.show();

    //change string and other data variables
    w->changeData("1234567890\nQWERTYU123\nLETTERS123\nWORDSSS123\n"
                  "TESTING123\nFUNCTIO123\nLETTERS123\nWORDSSS123\n", 10, 8);

    return a.exec();
}

Widget not updating properly

正如您所看到的那样,我们在main函数中设置的数据被截断,只打印前7个字符和前4行,基本上是我们在构造函数中设置的第一个字符串,并获取这个新字符串的子集并打印它 .

Without QScrollArea

删除QScrollArea修复了问题,但我需要我的应用程序的滚动功能 . 任何帮助将不胜感激 . 谢谢

回答(0)