Qt Study Note(5-2)

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);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章