[英]Can't add my Widget to a layout
为什么不能将小部件添加到布局? 就像添加小部件的示例一样。我的目标是绘制成一个小的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();
}
在私有区域的类头中:
QWidget * paintExample;
仔细阅读文档:
现在,要解决其他问题:
paintEvent()
创建无父母对象,而不删除它们。 这种方法不仅可以被频繁调用,而且这种绘画方法也不是很好。 据我了解, Note
已经是一个QWidget,因此您可以立即使用QPainter painter(this);
在其上进行绘画QPainter painter(this);
。 paintEvent()
进行带有布局的操作,以及显示/隐藏小部件。 在其他地方执行此操作,例如在窗口/对话框构造函数中。 为什么不能将小部件添加到布局?
因为QImage
不是QWidget
。 这就是为什么。 您可能应该将图像包装在QLabel
:
QLabel arrowLabel;
arrowLabel.setPixmap(QPixmap::fromImage(*arrowImg));
并将其传递给布局:
lay->addWidget(arrowLabel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.