首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带标题的QFrame

带标题的QFrame
EN

Stack Overflow用户
提问于 2019-10-23 02:02:01
回答 1查看 2K关注 0票数 2

我需要实现一个有标题的QFrame (见图)。然而,在阅读了QFrame的文档并试图重新实现paintEvent(QPaintEvent*)方法之后,我没有找到任何解决方案。

我想知道你们中是否有人能提供一个小例子,演示我如何实现这样的目标:

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-23 08:34:36

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

代码语言:javascript
复制
#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;
};

那就用..。

代码语言:javascript
复制
titled_frame tf("A Title Here");
auto *layout = new QVBoxLayout(&tf);
layout->addWidget(new QLabel("Any QLayout or QWidget here..."));
tf.show();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58514441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档