why the image appears at the corner of the window?
-
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),ui(new Ui::MainWindow),
start(0, 0), end(0, 0), firstClick(true){
ui->setupUi(this);
lbl=new Label(this);
QPixmap pix("C:/Users/Utilisateur/Documents/paint/icecream.jpg");lbl->setPixmap(pix);
}
MainWindow::~MainWindow()
{
delete ui;}
Label::Label(QWidget * parent)
: QLabel(parent){
}
void Label::mousePressEvent(QMouseEvent *pQEvent)
{
if (pQEvent->button() == Qt::LeftButton) {
(firstClick ? start : end) = pQEvent->pos();
firstClick = !firstClick;
update();
pQEvent->accept();
}
}
void Label::paintEvent(QPaintEvent *pQEvent)
{
QLabel::paintEvent(pQEvent);
if (!firstClick) return;
QPainter painter(this);
QPen pen(Qt::red);
pen.setWidth(4);
painter.setPen(pen);
painter.drawLine(start, end);
}void MainWindow::on_pushButton_clicked()
{
double distance=sqrt(pow(start.x()-end.x(), 2) + pow(start.y()-end.y(), 2));
ui->label->setText(QString::number(distance));
}.h
namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTQLabel *lbl;
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();protected:
Ui::MainWindow *ui;QPoint start, end; bool firstClick;
private slots:
void on_pushButton_clicked();
};
class Label : public QLabel
{public:
explicit Label(QWidget * parent);
private:QPoint start, end; bool firstClick;
protected:
void mousePressEvent(QMouseEvent *event);void paintEvent(QPaintEvent *event);
};
-
Because you're simply creating a QLabel with the dailog as parent but don't add it to the dialog's layout.
Why do you want to add it manually when you already creating a ui wih the designer where you also can but the label in?