简体   繁体   中英

MouseEvent coordinates on Qlabel with Image

so i dont know how to add a mouseevent ( if i click the label with image selected to add x,y coordinates of the mouse on the tableWidget and the coordinates to be drawed on the image ( green/red dots)

在此处输入图片说明

for now i only can open a ascii file with coordinates and image. i need your help with mouseevent and draw the points on the image

void design::on_loadtext1_clicked() {
ui->merge->setText("merge");
QString filename=QFileDialog::getOpenFileName(
            this,
            tr("Open File"),
            "C://",
            "Text File(*.txt)"

         );
QFile file(filename);
if(!file.open(QIODevice::ReadOnly)) { QMessageBox::information(nullptr,"Info",file.errorString());
}
QTextStream in(&file);
  double x = 0.0;
  double y = 0.0;
 // double xn = 532;
  int row=0;
  QString line;
  ui->tableWidget->setRowCount(30);
  ui->tableWidget->setColumnCount(2);

  while(!in.atEnd()) {
      line = in.readLine();
      QStringList s = line.split(" ");
      x = s.at(0).toDouble();
      y = s.at(1).toDouble();
         ui->tableWidget->setItem(row, 0, new TableItem(tr("%1").arg(x)));
         ui->tableWidget->setItem(row, 1, new TableItem(tr("%1").arg(y)));

      row++;
  } }

If you want to draw an ellipse on QLabel at mouse click position, this code should get you started:

First, as proposed, subclass QLabel :

.h file

#include <QLabel>
#include <QPainter>
#include <QMouseEvent>

class MyLabel : public QLabel
{
public:
    MyLabel(QWidget* parent=nullptr);
    void mousePressEvent(QMouseEvent * e);

private:
    QPixmap *pix;
};

Then create pixmap in constructor and implement drawing on mouseClickEvent :

.cpp file

MyLabel::MyLabel(QWidget *parent) :
    QLabel(parent)
{
    pix = new QPixmap(200,200);
    pix->fill(Qt::white);
    setPixmap(*pix);
}

void MyLabel::mousePressEvent(QMouseEvent *e)
{
    int xPos, yPos;
    if(e->button() == Qt::LeftButton)
    {
        xPos = e->pos().x();
        yPos = e->pos().y();
    }

    QPainter painter(pix);
    painter.setPen(Qt::black);
    painter.drawEllipse(xPos, yPos, 3, 3);

    setPixmap(*pix);

    QLabel::mousePressEvent(e);
}

Then just create an instance of MyLabel in MainWindow :

label = new MyLabel(this);
label->setGeometry(0,0,200,200);

Don't forget declaration in mainwindow.h :

MyLabel *label;

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM