简体   繁体   English

试图在QLabel上绘画失败(无法在没有对象的情况下调用成员函数'virtual void QLabel :: paintEvent(QPaintEvent *)')

[英]Trying to paint on a QLabel fails (cannot call member function 'virtual void QLabel::paintEvent(QPaintEvent*)' without object)

I have seen many examples on how to use a paintevent, but I just cannot get it to work. 我已经看过很多关于如何使用paintevent的例子,但我无法让它发挥作用。

I have in my .ui file a label named 'image' and I am trying to paint inside it. 我在.ui文件中有一个名为'image'的标签,我正在尝试在其中绘画。 I fail miserably. 我悲惨地失败了。 In most of the examples I've seen they use the 在我见过的大多数例子中,他们都使用了

QLabel::paintEvent(e)

but I cannot use this, I get: 但我不能用这个,我得到:

error: cannot call member function 'virtual void QLabel::paintEvent(QPaintEvent*)' without object

And, when I use 而且,当我使用时

ui->image->paintEvent(e);

I get 我明白了

/usr/include/qt4/QtGui/qlabel.h:141: error: 'virtual void QLabel::paintEvent(QPaintEvent*)' is protected

I seem to be missing something... That's the part of my code that I try to implement this: 我似乎错过了一些东西......这是我尝试实现的代码的一部分:

void crop_my_image::paintEvent(QPaintEvent *e)
{
    ui->image->paintEvent(e);
    QPainter painter(ui->image);
    painter.setPen(QPen(QBrush(QColor(0,0,0,180)),1,Qt::DashLine));
    painter.setBrush(QBrush(QColor(255,255,255,120)));
    painter.drawRect(selectionRect);
}

crop_my_image is of QDialog type! crop_my_image属于QDialog类型!

PS: If, instead of ui->image->paintEvent(e); PS:如果,而不是ui->image->paintEvent(e); I use QDialog::paintEvent(e); 我使用QDialog::paintEvent(e); I can successfully draw on my dialog, so I should be in the right path! 我可以成功地在我的对话框上画画,所以我应该走在正确的道路上!

Thanks in advance for any answers! 提前感谢您的任何答案!

You have to do exactly the same with label what you did with QDialog, which is create class which will inherit from QLabel and implement paintEvent function. 您必须使用QDialog对标签执行完全相同的操作,QDialog是将继承自QLabel并实现paintEvent函数的create类。 Example: 例:

//MyLabel.h
class MyLabel : public QLabel
{
    Q_OBJECT
    public:
        MyLabel(QWidget *parent = 0);
    private:
        void paintEvent(QPaintEvent *);
};

//MyLabel.cpp

MyLabel::MyLabel(QWidget *parent)
    : QLabel(parent)
{
    /*...*/

}

void MyLabel::paintEvent(QPaintEvent *)
{
    /* paint somehting on your label*/
}

And than you will be able to do: 而且你将能够做到:

void crop_my_image::paintEvent(QPaintEvent *e)
{
    myLabelObject->paintEvent(e);
    QPainter painter(ui->image);
    painter.setPen(QPen(QBrush(QColor(0,0,0,180)),1,Qt::DashLine));
    painter.setBrush(QBrush(QColor(255,255,255,120)));
    painter.drawRect(selectionRect);
}

But firstly, why event you want to invoke this method? 但首先,为什么要调用此方法的事件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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