#include <QtGui>
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->setAttribute(Qt::WA_StaticContents);
this->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
this->curColor = Qt::black;
this->zoom = 8;
image = QImage(16,16,QImage::Format_ARGB32);
image.fill(qRgba(0,0,0,0));
}
Widget::~Widget()
{
}
QSize Widget::sizeHint()const
{
QSize size = zoom * image.size();
if(zoom >= 3)
size += QSize(1,1);
return size;
}
void Widget::setPenColor(const QColor& newColor)
{
curColor = newColor;
}
void Widget::setIconImage(const QImage& image)
{
if(this->image != image)
{
this->image = image.convertToFormat(QImage::Format_ARGB32);
update();
this->updateGeometry();
}
}
void Widget::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
if(zoom >=3)
{
painter.setPen(this->palette().foreground().color());
for(int i = 0; i <= image.width();++i)
painter.drawLine(zoom*i,0,zoom*i,zoom*image.height());
for(int j = 0;j <= image.height();j++)
painter.drawLine(0,zoom*j,zoom*image.width(),zoom*j);
}
for(int i = 0; i < image.width();i++)
{
for(int j = 0;j < image.height();j++)
{
QRect rect = this->pixelRect(i,j);
if(!event->region().intersect(rect).isEmpty())
{
QColor color = QColor::fromRgba(image.pixel(i,j));
if(color.alpha() < 255)
painter.fillRect(rect,Qt::white);
painter.fillRect(rect,color);
}
}
}
}
QRect Widget::pixelRect(int i, int j) const
{
if(zoom >=3)
return QRect(zoom*i+1,zoom*j+1,zoom-1,zoom-1);
return QRect(zoom*i,zoom*j,zoom,zoom);
}
void Widget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
setImagePixel(event->pos(),true);
else if(event->button() == Qt::RightButton)
setImagePixel(event->pos(),false);
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
setImagePixel(event->pos(),true);
else if(event->buttons() & Qt::RightButton)
setImagePixel(event->pos(),false);
}
void Widget::setImagePixel(const QPoint &pos, bool opaque)
{
int i = pos.x()/zoom;
int j = pos.y()/zoom;
if(image.rect().contains(i,j))
{
if(opaque)
image.setPixel(i,j,penColor().rgba());
else
image.setPixel(i,j,qRgba(0,0,0,0));
this->update(this->pixelRect(i,j));
}
}
void Widget::setZoomFactor(int newZoom)
{
if(newZoom < 1)
newZoom = 1;
if(newZoom != zoom)
{
zoom = newZoom;
update();
updateGeometry();
}
}
几点说明:
1.宏 Q_PROPERTY 声明属性读写属性
2.setSizePolicy(.,.) 说明控件最小尺寸为推荐尺寸
3.sizeHint() 获得控件推荐尺寸
4.控件 update()/updateGeometry()用于下次重绘和调整控件尺寸
5.在函数paintEvent中绘制图元
6.一个控件的调色板有3个颜色组 激活,非激活,不可用