QFrame с заголовком - PullRequest
       60

QFrame с заголовком

0 голосов
/ 23 октября 2019

Мне нужно реализовать QFrame с заголовком ( см. Изображение ). Однако, прочитав документацию QFrame и попытавшись повторно реализовать метод paintEvent(QPaintEvent*), я не смог найти никакого решения.

Мне было интересно, может ли кто-нибудь из вас представить небольшой пример, демонстрирующий, как я могу достичь чего-то подобногоэто:

enter image description here

Спасибо!

1 Ответ

1 голос
/ 23 октября 2019

В качестве альтернативы созданию собственного составного виджета вы можете использовать поля содержимого для подделки строки заголовка ...

#include <QFont>
#include <QFrame>
#include <QPainter>

class titled_frame: public QFrame {
    using super = QFrame;
public:
    explicit titled_frame (const QString &title = "A Title Here", QWidget *parent = nullptr)
        : super(parent)
        , m_title(title)
        {
            /*
             * Set the top margin based on the font height.
             */
            setContentsMargins(0, 2 * fontInfo().pixelSize(), 0, 0);
        }
protected:
    virtual void paintEvent (QPaintEvent *event) override
        {

            /*
             * Draw the title centred in the top margin.
             */
            QPainter painter(this);
            QRect title_rect(QPoint(0, 0), QSize(width(), contentsMargins().top()));
            painter.fillRect(title_rect, Qt::blue);
            painter.setPen(Qt::black);
            painter.drawText(title_rect, Qt::AlignCenter, m_title);

            /*
             * Defer to the base class implementation to update everything else.
             */
            super::paintEvent(event);
        }
private:
    QString m_title;
};

Затем использовать в качестве ...

titled_frame tf("A Title Here");
auto *layout = new QVBoxLayout(&tf);
layout->addWidget(new QLabel("Any QLayout or QWidget here..."));
tf.show();
...