自定义控件和自定义样式表

#ifndef SWIDGET_H
#define SWIDGET_H

#include <QWidget>

class SWidget : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(QColor lineColor READ getLineColor WRITE setLineColor DESIGNABLE true)
    Q_PROPERTY(QColor rectColor READ getRectColor WRITE setRectColor DESIGNABLE true)

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

    QColor getLineColor() const;
    void setLineColor( QColor c );

    QColor getRectColor() const;
    void setRectColor( QColor c );


protected:
    void paintEvent( QPaintEvent *e );

private:
    QColor lineColor;
    QColor rectColor;
};

#endif // SWIDGET_H


#include "swidget.h"

#include <QPainter>
#include <QDebug>

SWidget::SWidget(QWidget *parent) :
    QWidget(parent)
{
}

SWidget::~SWidget()
{
}

void SWidget::paintEvent( QPaintEvent *e )
{
    QPainter p(this);
    p.setPen( getLineColor() );
    p.drawLine( 0,0, size().width(), size().height() );
    p.setPen( getRectColor() );
    p.drawRect( 5,5, size().width()-10, size().height()-10 );
}

QColor SWidget::getLineColor() const
{
    return lineColor;
}

void SWidget::setLineColor( QColor c )
{
    qDebug() << __FUNCTION__;
    lineColor = c;
}

QColor SWidget::getRectColor() const
{
    return rectColor;
}

void SWidget::setRectColor( QColor c )
{
    qDebug() << __FUNCTION__;
    rectColor = c;
}


#include <QtGui/QApplication>
#include "mainwindow.h"
#include "swidget.h"
#include <QFile>

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

    //create widget
    SWidget *w = new SWidget();

    //open and set style sheet
    QFile f( "sheet.qss" );
    if( f.open( QFile::ReadOnly ) )
    {
        QString ssheet = QLatin1String( f.readAll() );
        a.setStyleSheet( ssheet );
    }

    w->show();

    return a.exec();
}


以上是定义控件

下面是对控件的属性 通过样式表来修改

SWidget
{
 qproperty-lineColor: yellow;
 qproperty-rectColor: red;
}

也是种方法,通过样式表实现对控件ui的设置,好东西

http://qt-project.org/wiki/Qt_Style_Sheets_and_Custom_Painting_Example

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值