3
Hello, I’m with a screen project using Qt Creator and I’m stuck with the following problem: I want to track the mouse coordinates by moving the cursor over a Qlabel. I saw in some other topics some cases solved, but always had to create a Class manually for Qlabel, as I used the Qt editor Creator so it became more difficult to change the Qlabel class. Below is the method that would activate the mouse tracking on the screen.
void mainwindow::on_ButtonAddFileira_clicked(){
this->pTimer.disconnect();
QImage image;
image.load("C:/Users/Syn/Desktop/TCC/Fotos Bolsão FEI/02 Bolsao_Cheio_Foreground.jpg");
//image = MatToQImage(this->ImagemBase.capturaImgBuffer());
ui->labelScreen->setPixmap(QPixmap::fromImage(image));
ui->labelScreen->setScaledContents(true);
ui->labelScreen->setMouseTracking(true);
}
The idea is that when you click a button, the mouse tracking is activated and I can identify your x,y coordinates in the qLabel image. Below a method that may help but I’m not sure how to use it:
bool mainwindow::eventFilter(QObject *obj, QEvent *event){
if (qobject_cast<QLabel*>(obj)== ui->labelScreen && event->type() == QEvent::MouseMove)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
qDebug() << QString("Mouse move (%1,%2)").arg(mouseEvent->pos().x()).arg(mouseEvent->pos().y());
ui->label_X->setText(QString().arg(mouseEvent->pos().x()));
ui->label_Y->setText(QString().arg(mouseEvent->pos().y()));
}
return false;
}
Would anyone know how to do that with the editor-generated fixed Qlabel, i.e., without creating a separate Label class? Thanks in advance.
First thank you for the answer, but now after creating the above class and calling the method 'Qmouseevent::pos()', I get 2 error messages, they are they: no matching Function for call to 'Myimagelabel::Myimagelabel(Qwidget*&)' myimage = new Myimagelabel(mainwindow); and the other is _cannot call Member Function 'Qpoint Qmouseevent::pos() const' without Object _ would know what is causing this error?
– Yuri Pires
Make sure you have correctly declared the class constructor, it should receive a pointer to
QWidget
and call the parent class constructor by forwarding this pointer. You can also create the class by Qt Creator by going toFile
->New File or Project
->C++
->C++ Class
. UseQLabel
in the fieldBase class
andQWidget
in the fieldType information
.– Cahe
Valew friend, I tried the first way with Qtimer and it worked, by the subclass method I tried but my compiler insists on error in the constructor, although I believe I have declared everything correctly. But thanks for your help.
– Yuri Pires