2012-04-10 107 views
2

我正面临处理Qt中的点击问题。我有以下类:Qt对象信号未连接到方法(处理程序)

class MyRectItem : public QObject, public QGraphicsEllipseItem{ 
    Q_OBJECT 
public:  
    MyRectItem(double x,double y, double w, double h) 
    : QGraphicsEllipseItem(x,y,w,h)  
    {} 

public slots:  
    void test() { 
     QMessageBox::information(0, "This", "Is working"); 
     printf("asd"); 
    } 
signals:  
    void selectionChanged(bool newState); 

protected:  
    QVariant itemChange(GraphicsItemChange change, const QVariant &value) { 
     if (change == QGraphicsItem::ItemSelectedChange){ 
      bool newState = value.toBool(); 
      emit selectionChanged(newState); 
     } 
     return QGraphicsItem::itemChange(change, value); 
    } 
}; 

现在我想插槽连接到信号,我做了以下内容:

MyRectItem *i = new MyRectItem(-d, -d, d, d); 
     i->setPen(QPen(Qt::darkBlue)); 
     i->setPos(150,150); 
     // canvas is a QGraphicsScene 
     canvas.addItem(i); 
     i->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable); 
     QObject::connect(&canvas, SIGNAL(selectionChanged(bool)), this, SLOT(test())); 

当我运行此,显示在canvas圆但是当我点击该圈没有任何反应和控制台显示以下内容:

Object::connect: No such signal QGraphicsScene::selectionChanged(bool) 

有什么建议吗?

回答

2

控制台消息是您的答案。由于您还没有指定您使用的Qt版本,我以前认为4.8是最新的稳定版本。正如从here可以看出,是不是真的有这样的信号来作为

selectionChanged(bool) 

然而,有一个信号

selectionChanged() 
4

您是否尝试过这个已经:

QObject::connect(&canvas, SIGNAL(selectionChanged()), this, SLOT(test())); 

由于据我所知,从QGraphicsScene中选择的信号没有任何参数:http://qt-project.org/doc/qt-4.8/qgraphicsscene.html#selectionChanged

这里您试图将QGRaphicsScene的信号连接到插槽'test',而不是您在MyRectItem中定义的信号。如果您想要连接从MyRectItem信号,你应该这样做:

QObject::connect(i, SIGNAL(selectionChanged(bool)), this, SLOT(test())); 

第一个参数是信号源(发件人)。

杰拉德