Custom QGraphicsItems not compiling and gives “obj

2019-07-30 06:47发布

问题:

I am trying to create a Custom QGraphicsItem button as shown by Fred here. The code which he posted can be found here.

The problem is when I try and compile the code I get the following two errors:

  • /usr/include/qt4/QtGui/qgraphicsitem.h ‘QGraphicsItem::QGraphicsItem(const QGraphicsItem&)’ is private
  • /usr/include/qt4/QtCore/qobject.h
    ‘QObject::QObject(const QObject&)’ is private

Here is the code snippet which essentially is the same as that in the sample above. The error is on the class deceleration.

class MyButton : public QObject, public QGraphicsItem
{
 Q_OBJECT
 Q_INTERFACES(QGraphicsItem)

public:
 MyButton(QGraphicsItem *parent = 0);
 MyButton(const QString normal, const QString pressed = "", QGraphicsItem *parent = 0);
....
}

Interestingly the other sample as shown here works fine. The sample code for that can be found here.

Any idea what is wrong? Thanks in advance.

回答1:

Those errors looks like an attempt to copy the button object. Compiler tries to generate MyButton copy constructor automatically and fails, because copy constructor of QObject (which is your button base) is private. Besides the errors you listed you should also see stuff like:

note: synthesized method 'MyButton::MyButton(const MyButton&)' first required here

with source file name and line number following this message. If you don't see this message, try adding:

private:
    Q_DISABLE_COPY(MyButton)

to the MyButton class definition. Then you should see this:

error: 'MyButton::MyButton(const MyButton&)' is private within this context