Event() : 事件处理器,每一个都对应一种类型的事件
When invoking paintEvent()
- In widget first displaying , system will generate a paint event
- In adjusting widget size, system will also generate a paint event
- In widget hiding and emerging, system will paint hiding area
Two methods for painting
QWidget :: update() | QWidget::repaint() |
---|---|
paint in next event | immediately paint |
void IconEditor::paintEvent(QPainEvent *event)
{
QPainter painter(this);
if (zoom >= 3)
{
painter.setPen(palette().foreground().color()); // 使用调色板设置颜色
for (int i = 0; i <= image.width(); ++i) // vertical line
{
painter.drawline(zoom * i, 0, zoom * i, zoom * image.height());
/* 左边两个为坐标起点,右边两个为坐标终点 */
/* Qt窗口部件左上角处的位置坐标为(0,0) */
}
for (int j = 0; j <= image.height(); ++j) // horizontal line
{
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 = pixelRect(i, j);
if (!event->region().intersect(rect).isEmpty())
{
QColor color = QColor::fromRgba(image.pixel(i, j));
if (color.alpha() < 255) // paint background
painter.fillRect(rect, Qt::White);
painter.fillRect(rect, color); // fill rectangular
}
}
}
}
}
QRect IconEditor::pixelRect(int i, int j) const
{
if (zoom >= 3)
{
return QRect(zoom * i + 1, zoom * j + 1, zoom - 1, zoom - 1);
// QRect(x, y, width, height)
}
else
{
return QRect(zoom * i, zoom * j, zoom, zoom);
}
}
Three Color Groups of Palette(调色板)
- Active(激活组)
supply in current active windows’s widgets - Inactive(非激活组)
supply in other window’s widgets - Disabled(不可用组)
supply in disabled widgets
void IconEditor::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
setImagePixel(event->pos(), true);
}
else if (event->button() == Qt::RightButton)
{
setImagePixel(event->pos(), false);
}
}
void IconEditor::mouseMoveEvent(QMouseEvent *event)
{
/*
若是同时按下多个键,最终结果实际为QMouseEvent::buttons()
的返回值与鼠标的按键按照位或(|)运算的结果,因此需要
位与(&)来判断是否按下某个特定键
*/
if (event->button() & Qt::LeftButton)
{
setImagePixel(event->pos(), true);
}
else if (event->button() & Qt::RightButton)
{
setImagePixel(event->pos(), false);
}
}
void IconEditor::setImagePixel(const QPoint &pos, bool opaque)
{
int i = pos.x() / zoom;
int j = pos.y() / zoom;
if (image.rect().contains(i, j))
{
if (opaque) // opaque(不透明的)
{
image.setPixel(i, j, penColor().rgba());
}
else
{
image.setPixel(i, j, qRgba(0, 0, 0, 0));
}
update(pixelRect(i, j);
}
}