繁体   English   中英

无法将我的小部件添加到布局

[英]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;

仔细阅读文档:

  • QHBoxLayout和任何其他布局只能容纳从QLayoutItem继承的项目,这些项目是QLayout本身,QSpacerItem和QWidgetItem。 创建QWidget并在其上绘画。
  • QPainter构造函数接受QPaintDevice的后代,而QWidget就在其中,因此这是完全可能的。

现在,要解决其他问题:

  • 您可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM