带标题的QFrame

时间:2019-10-23 02:02:01

标签: c++ qt qwidget paintevent qframe

我需要实现一个带有标题的QFrame(参见图片)。但是,在阅读QFrame的文档并尝试重新实现paintEvent(QPaintEvent*)方法之后,我找不到任何解决方案。

我想知道你们中是否有人可以提供一个小例子来说明我如何实现这样的目标:

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:1)

作为创建自己的复合小部件的替代方法,您也许可以使用内容边距来伪造标题栏...

#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();