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