0

My code is:but I can't find image in QWidget. What can I do if i want to show the image ? And what's wrong with my code?

QTtest::QTtest(QWidget *parent)
: QWidget(parent)
{
QHBoxLayout * m_viewLayout = new QHBoxLayout();
this->setLayout(m_viewLayout);

QHBoxLayout * showLayout = new QHBoxLayout();
QHBoxLayout * btnLayout = new QHBoxLayout();

m_viewLayout->addLayout(showLayout);
m_viewLayout->addLayout(btnLayout);

widget1 = new QWidget();
showLayout->addWidget(widget1);


QPixmap image("C:\\Users\\zhq\\Desktop\\1.png");
QPainter painter(widget1);
painter.drawPixmap(QPoint(0,0),image);


widget2 = new QWidget();
showLayout->addWidget(widget2);


QPushButton * btn = new QPushButton("btn");
btnLayout->addWidget(btn);

showLayout->addStretch();
}
yingzi
  • 25
  • 5

1 Answers1

0

There's a couple of thing wrong with your code. Assuming that the image is loaded correctly, you should paint the image in the void QWidget::paintEvent(QPaintEvent * event) of your widget. Do not paint outside of paint events. Also, as you're currently doing it, the image will be overwritten the next time the widget updates/reapints itself anyway. You might consider going an easier route and use a QLabel in your layout instead of widget1. You can then call QPixmap::fromImage() to convert the image to a pixmap and QLabel::setPixmap() on the label to display your image.

Bim
  • 1,008
  • 1
  • 10
  • 29
  • 1. Even I draw the image in the paintEvent, it doesn't work. 2. If I show the image by setPixmap in QLabel, there is another problem. When the QDialog resize, I find the QLabel will remain the same size, it will not resize when the Qdialog resize. – yingzi Sep 21 '15 at 09:26
  • Try the QLabel approach. It is much simpler. – Bim Sep 21 '15 at 09:28
  • Yes, I have tried the QLabel, and it actually worked. But, I find there is something wrong with showLayout->addStretch(). I find the image is invisible if I add showLayout->addStretch(); but, the image is visible if i don't add it. – yingzi Sep 21 '15 at 09:46
  • You might have a problem with your layouts then. Qt layouts need some time to master. Read up on them [here](http://doc.qt.io/qt-5/layout.html). Without the new code it is hard to tell... You might take a look at [this](http://stackoverflow.com/questions/20452754/how-exactly-does-addstretch-work-in-qboxlayout) and [this](http://stackoverflow.com/questions/20452754/how-exactly-does-addstretch-work-in-qboxlayout). If the answer solves the problem you posted, please accept it. For a new problem, post a new question after you've first tried solving it yourself. – Bim Sep 21 '15 at 09:55