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

时间:2016-04-27 19:05:20

标签: c++ qt

我在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

1 个答案:

答案 0 :(得分:0)

您需要使用QGraphicsViewdocs)和QGraphicsScenedocs):

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;
};

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