Qt / QWidget、QFrame 区别

QFrame 是基本控件的基类,QWidget 是 QFrame 基类,关系如下:

QWidget <- QFrame <- QPushButton,QLabel…

我们经常会从 QFrame 或者 QWidget 继承然后自定义一个复杂的 widget,在设置样式表的时候它们就有一个大的区别。 

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QFrame>
#include <QStyleOption>
#include <QStyle>
#include <QPainter>

namespace Ui {
class Dialog;
}

class MyWidget : public QWidget {
    Q_OBJECT
public:
    MyWidget(QWidget *parent = 0) : QWidget(parent) {
        this->setStyleSheet("QWidget{background:#ff0000;} QWidget:hover{background:#00ff00;}");
    }

//protected:
//    virtual void paintEvent(QPaintEvent *event) override
//    {
//        Q_UNUSED(event);
//        QStyleOption opt;
//        opt.init(this);
//        QPainter p(this);
//        style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
//    }
};

class MyFrame : public QFrame {
    Q_OBJECT
public:
    MyFrame(QWidget *parent = 0) : QFrame(parent) {
        this->setStyleSheet("QWidget{background:#ff0000;} QWidget:hover{background:#00ff00;}");
    }
};

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    setFixedSize(QSize(400,300));

    MyWidget *widget = new MyWidget(this);
    MyFrame *frame = new MyFrame(this);
    widget->setFixedSize(50, 50);
    frame->setFixedSize(50, 50);
    widget->move(0, 0);
    frame->move(0, 50);
}

Dialog::~Dialog()
{
    delete ui;
}

 如下图,发现从 QWidget 继承过来的 MyWidget 并没有显示出样式来。

具体原因还不是很清楚,不过下面一段话可能对我们有些帮助:

QWidget Supports only the background, background-clip and background-origin properties.

If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:

void CustomWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

The above code is a no-operation if there is no stylesheet set.

Warning: Make sure you define the Q_OBJECT macro for your custom widget。

 

转载于:QFrame与QWidget的区别_Keep It Simple, Stupid-CSDN博客

 

(SAW:Game Over!) 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值