Qt:为什么我的按钮没有信号?

时间:2013-03-07 02:35:30

标签: qt signals-slots emit

为什么按钮对象在单击按钮时没有得到sigKK()信号?

当发出信号时,所有qt对象都能接收到此信号吗?

代码如下:

class PushButton :  public QPushButton
{
    Q_OBJECT
signals:
    void sigKK();
};

PushButton类继承自QPushButton,但不在此处连接信号和插槽。这是对的吗?

class MainWindow : public QMainWindow
{
    Q_OBJECT    
public:
    explicit MainWindow(){
        resize(400,200);    
        connect(this,SIGNAL(sigKK()),this,SLOT(showRecv1()));   

        button = new PushButton();
        button->setText("Hello,All");
        button->resize(40,15);
        connect(button, SIGNAL(clicked()),this,SLOT(buttonCK()));
        connect(button, SIGNAL(sigKK()),this,SLOT(showRecv2()));
            //**I can connect sigKK signal with showRecv2 slot here ?**** 
        button->show();
    }
    ~MainWindow(){      
    }
signals:
    void sigKK();
public slots:
    void showRecv1(){
        cout<<"recved 1"<<endl;
        resize(100,100);
    }
    void showRecv2(){
        cout<<"recved 2"<<endl;
        button->setText(".....");
    }
    void buttonCK(){
        emit sigKK();
        cout<<"emited"<<endl;
    }
private:
    PushButton *button ; 
};
#endif

1 个答案:

答案 0 :(得分:1)

  

当发出信号时,所有qt对象都可以接收到此信号吗?

即可。当发出信号时,它仅由连接有信号或插槽的QObjects接收。

您的MainWindow和PushButton都有一个同名信号......但它们仍然是不同的信号。它们彼此完全无关。当MainWindow发出sigKK时,这对PushButton的sigKK没有影响。

在您的示例中,sigKK似乎完全不必要。也许您可以将clicked()直接连接到您想要执行的操作?

connect(button, SIGNAL(clicked()),this,SLOT(showRecv1()));
connect(button, SIGNAL(clicked()),this,SLOT(showRecv2()));