gpt4 book ai didi

c++ - 如何在Qt中的特定坐标上显示图像?

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:03 25 4
gpt4 key购买 nike

我在 Qt 中有这个对话框窗口类:

class Board : public QDialog
{
Q_OBJECT

public:
explicit Board(QWidget *parent = 0);
~Board();

private:
Ui::Board *ui;

void mousePressEvent(QMouseEvent *mouseEvent);
};

我想在函数 mousePressEvent 中根据用户给定的坐标显示 png 图像,每次用户单击对话框窗口中的某处时都会调用该函数。所以我需要像 displayImage("path/to/image.png", coordX, coordY); 这样的东西。我该怎么做?

新代码:

class Board : public QDialog
{
public:
Board(QWidget *parent = 0) :
QDialog(parent),
ui(new Ui::Board),
view(&scene)
{
// Set background image
/**************/
ui->setupUi(this);

QPixmap pix("path/background.png");
ui->label_board->setPixmap(pix);

/**************/
/ Set layout for displaying other images on the background
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(&view);
//or set the layout and the view in the designer if using Qt Creator
}

protected:
virtual void mousePressEvent(QMouseEvent *mouseEvent) override
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(QPixmap("path/to/image.png"));
scene.addItem(item);
item->setPos(coordX, coordY);
}

private:
Ui::Board *ui;
QGraphicsScene scene;
QGraphicsView view;
};

label_board 是使用 Qt Designer 设置到某个位置的 500x500 标签。

enter image description here

最佳答案

您将需要使用 QGraphicsView ( docs ) 和 QGraphicsScene ( docs ):

class Board : public QDialog
{
public:
Board(QWidget *parent = 0) :
QDialog(parent),
ui(new Ui::Board),
view(&scene)
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(&view);
//or set the layout and the view in the designer if using Qt Creator

//EDIT: add background like this first
QGraphicsPixmapItem *background = QGraphicsPixmapItem(QPixmap("path/to/background.png"));
scene.addItem(background);
background.setPos(0, 0); //position it to cover all the scene so at 0,0 which is the origin point
background.setScale(2.0); //scale the image to the scene rectangle to fill it
background.setZValue(-0.1); //to ensure it is always at the back
}

protected:
virtual void mousePressEvent(QMouseEvent *mouseEvent) override
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(QPixmap("path/to/image.png"));
scene.addItem(item);
item->setPos(coordX, coordY);
}

private:
Ui::Board *ui;
QGraphicsScene scene;
QGraphicsView view;
};

差不多就这些了。另请注意,该位置是项目(图像)左上角的位置。如果您想将其居中,则需要根据项目(图像)的比例调整位置。

关于c++ - 如何在Qt中的特定坐标上显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36898753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com