2012-04-10 41 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())); 

第一個參數是信號源(發件人)。

傑拉德