如何在QGraphicsView中显示图像

时间:2018-04-06 07:09:44

标签: c++ qt

我在mainwindow.ui文件中创建了一个Graphics View对象,我试图在其中显示图像。对于TextBrowser对象,我就是这样做的

QTextBrowser *textBrowser_Actors = this->findChild<QTextBrowser*>("textBrowser_Actors");
textBrowser_Actors->setText(QString::fromUtf8(movie.get_actors().c_str()));

类似地,如何通过以下方法找到GraphicsView后设置图像?

QGraphicsView* movie_poster = this->findChild<QGraphicsView*>("movie_poster");

我在谷歌上搜索过以下内容,但到目前为止还无法正常工作。

QGraphicsScene* scene = new QGraphicsScene();
movie_poster->setScene(scene);
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage("movie.jpg"));
scene->addItem(item);
movie_poster->show();

编辑-1

int main(int argc, char *argv[])
{
    std::vector<Movie> movie_vector; // This is where movie DB will be read to, and new movies will be added to
    MainWindow w;
    w.setWindow(movie_vector[0]); // calling setWindow with first movie
    w.show();
    return a.exec();
}

//setWindow definition    
void MainWindow::setWindow(Movie &movie) {

// Next two lines gets the textBrowser object and set its value to movie title
    QTextBrowser *textBrowser_Title = this->findChild<QTextBrowser*>("textBrowser_Title");
    textBrowser_Title->setText(QString::fromUtf8(movie.get_title().c_str()));

// This is where I'm trying to get GraphicsView object and set an image in it.
    QGraphicsView* movie_poster = this->findChild<QGraphicsView*>("movie_poster");
    QGraphicsScene* scene = new QGraphicsScene();
    movie_poster->setScene(scene);
    QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap("C:\Users\Name\Desktop\codes\Qt\MovieDB\titanic.jpg"));
    scene->addItem(item);
    movie_poster->show();
}

1 个答案:

答案 0 :(得分:-1)

您也可以输出QLabel的图像。

//I suppose you haven't a QLabel in you .ui
QLabel* label = new QLabel(this);
QPixmap image(":/path/to/image.png");

label->setPixmap(image);
//Optional
label->setBackgroundRole(QPalette::Base);
label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
label->setScaledContents(true);

label->show();