Advertisement

QT信号槽总结-connect函数错误用法

阅读量:

QT库的qobject.h
connect函数声明:connect函数用于建立信号与槽之间的连接,QT库提供了三种实现:

复制代码
    static QMetaObject::Connection connect(const QObject *sender, const char *signal,
                        const QObject *receiver, const char *member, Qt::ConnectionType = Qt::AutoConnection);
    
    
复制代码
    static QMetaObject::Connection connect(const QObject *sender, const QMetaMethod &signal,
                    const QObject *receiver, const QMetaMethod &method,
                    Qt::ConnectionType type = Qt::AutoConnection);
    
    
复制代码
    inline QMetaObject::Connection connect(const QObject *sender, const char *signal,
                        const char *member, Qt::ConnectionType type = Qt::AutoConnection) const;
    
    
复制代码
    class ConnectCamera : public QWidget
    {
    	Q_OBJECT
    
    public:
    	ConnectCamera(QWidget *parent = Q_NULLPTR);
    	~ConnectCamera();
    	
    public slots:
    	void onConnectBtnSolt();
    	void onCancelBtSolt();
    	void onErrorMess(const QString & _errorMess);
    signals:
    	void signalConnectCamera(const QString& _ip, const QString& _user, const QString& _pass);
    private:
    	Ui::ConnectCamera ui;
    };
    
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-19/j4XF3mlaNHCsDU6pYfbPhWg5yE0c.png)

使用QT库提供的第一种实现方式,来绑定信号与槽
正确用法1:

复制代码
    connect(ui.okButton, SIGNAL(clicked()), this, SLOT(onConnectBtnSolt()));
    connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(onCancelBtSolt()));
    
    

错误用法1:

复制代码
    connect(ui.okButton, SIGNAL(clicked()), this, SLOT(onConnectBtnSolt));
    
    

原因分析:
用法1调用的connect函数实际为:

复制代码
    static QMetaObject::Connection connect(const QObject *sender, const char *signal,
                        const QObject *receiver, const char *member, Qt::ConnectionType = Qt::AutoConnection);
                        
    // SLOT的定义
    Q_CORE_EXPORT const char *qFlagLocation(const char *method);
    # define SLOT(a)     qFlagLocation("1"#a QLOCATION)
    
    

qt中的信号槽,实际用的是回调函数,onConnectBtnSolt()被解析为函数,onConnectBtnSolt格式判断会出错
网上很详细的讲解,QT版本可能早于5.9.6
QT QObject::connect函数的学习

全部评论 (0)

还没有任何评论哟~