如何在Qt中的特定坐标上显示图像?
我有这样的对话窗口类的Qt:如何在Qt中的特定坐标上显示图像?
class Board : public QDialog
{
Q_OBJECT
public:
explicit Board(QWidget *parent = 0);
~Board();
private:
Ui::Board *ui;
void mousePressEvent(QMouseEvent *mouseEvent);
};
我想dislay用户给定坐标PNG图像的功能mousePressEvent
,这被称为每当用户点击对话窗口上的某个地方。所以我需要像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
是500×500的标签设置为使用Qt Designer一些位置。
您将需要使用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;
};
这是相当多了。另请注意,该位置是该项目左上角的位置(图像)。如果你想要居中,你需要根据物品的比例(图像)来调整位置。
非常感谢!现在的问题是,我已经在对话框窗口中显示了一个图像标签,我希望新图像(您告诉我如何显示该图像)显示在所提及标签的顶部,以便标签将是一个静态背景,我想添加和删除其他图像,因为我需要。我将它添加到上面的代码中。 –
@ T.Syk你可以用同样的方式设置QGraphicsScene的背景图像。我强烈建议使用QGraphicsScene来进行所有的图像渲染。 QLabel的方法是可能的,但意图是为了不同的目的(不是作为背景进行进一步的工作,就像一块板子一样,所以你可以简单地将背景自己添加到场景中,就像我先显示的那样) – Resurrection
@ T.Syk I have编辑我的答案以覆盖背景图像以及对话框的构造函数,还可以在场景中设置背景画笔()。此外,您可能希望将背景的z pozition(setZValue)调整为-0.1之类的内容以确保背景将会总是在背景中,而不是遮住你以后添加的任何东西 – Resurrection
这并不完全清楚你想要做什么,你向我们展示的代码什么都不做。 –
对不起,我以为我很清楚。我试图更好地解释。是的,代码什么都不做,因为我问你如何做我不能做的事情,所以我怎么能把它写到我的问题上呢? –
我认为你的编辑实际上做得很好。 –