I am currently working on a GUI Project with Qt C++. A part of my work consists of tracking the mouse movement and marking its position with a green pixel. The tracking should occur only on a certain image, which is stored in a label.
So far, the tracking of the mouse has worked fine and I have been able to extract the coordinates from the QMouseEvent. However, I seem to have difficulties coloring the pixel the mouse is on. What I want is just a colored pixel which marks continuously where the mouse is, but I'm getting all the pixels colored on which the mouse is, and the image doesn't seem to update too. When I walk over, all I get is a black label (the image is wiped out) and ALL the green pixels where I have been with my mouse. However it should color ONLY the current pixel ON the existing image, and then it should refresh to the next position. Here is the function I have implemented for this:
QPoint current = event->pos();
QPoint localPos = ui->label_image_2->mapFromParent(current);
if(ui->label_image_2->rect().contains((localPos))){
image.setPixel(localPos.x(),localPos.y(), qRgb(0,255,0));
ui->label_image_2->setPixmap(QPixmap::fromImage(image));
When I walk through the image on label_2, the current position ON the image should be marked green. Am I missing something, or is my general approach wrong?
Where does your image
variable come from? It doesn't have the correct contents. You were probably setting some image on the label, but instead you should set that image on the image
member variable, and use that to set on the label.
I was able to fix it, turned out, I had declared image as a global QImage variable, however I had called the function as
draw(image,,...)
. Calling it asdraw(&image,,...)
fixed the problem!