Qt Study Note(5-2)
阿新 • • 發佈:2018-12-16
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);
}
}