#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