[英]Can't add my Widget to a layout
Why can't I add my widget to the layout? 为什么不能将小部件添加到布局? It is like the example for adding Widgets... My aim is to draw into a small QWidget, whichs purpose is only to hold that painted element.
就像添加小部件的示例一样。我的目标是绘制成一个小的QWidget,其目的只是保留该绘制的元素。
void Note::paintEvent(QPaintEvent *event)
{
paintExample = new(QWidget);
paintExample->setGeometry(500,500,500,500);
paintExample->setStyleSheet("background:yellow");
QImage *arrowImg = new QImage(100,100,QImage::Format_RGB32);
QHBoxLayout *lay = new QHBoxLayout;
lay->addWidget(arrowImg); //Error: no matching function for call to 'QHBoxLayout::addWidget(QImage*&)'
paintExample->setLayout(lay);
QPainter painter(arrowImg); //Must paint on QImage/QPixmap/QPicture, QWidget not possible?
if (painter.isActive()){
painter.begin(arrowImg);
painter.setPen(Qt::black);
QRect rect = QRect(50,25,60,40);
painter.drawRect(rect);
painter.end();
}
paintExample->show();
}
In the class header in private area: 在私有区域的类头中:
QWidget * paintExample;
Read the documentation carefully: 仔细阅读文档:
Now, to other issues: 现在,要解决其他问题:
paintEvent()
without deleting them. paintEvent()
创建无父母对象,而不删除它们。 Not only this method could be called quite frequently, this approach to painting is not good at all. Note
is a QWidget already, so you're free to paint on it right away, with QPainter painter(this);
Note
已经是一个QWidget,因此您可以立即使用QPainter painter(this);
在其上进行绘画QPainter painter(this);
. paintEvent()
either, as well as showing/hiding widgets. paintEvent()
进行带有布局的操作,以及显示/隐藏小部件。 Do this somewhere else, eg in your window/dialog constructor. Why can't I add my widget to the layout?
为什么不能将小部件添加到布局?
Because QImage
is not a QWidget
. 因为
QImage
不是QWidget
。 That's why. 这就是为什么。 You should probably wrap the image in a
QLabel
: 您可能应该将图像包装在
QLabel
:
QLabel arrowLabel;
arrowLabel.setPixmap(QPixmap::fromImage(*arrowImg));
and pass that to the layout: 并将其传递给布局:
lay->addWidget(arrowLabel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.