QT入门笔记--建立连接--connect()

这篇博客介绍了QT编程中的关键操作——使用connect()建立信号与槽的连接,详细解析了其工作原理和常见应用场景,通过实例展示了如何正确使用connect()实现组件间的通信,帮助初学者掌握QT开发中的这一核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <QApplication>
#include<QPushButton>

int main(int argc, char *argv[])
{
    QApplication myapp(argc, argv);
    QPushButton *btn = new QPushButton("Quit");
    QObject::connect(btn,SIGNAL(clicked()),&myapp,SLOT(quit()));
    btn->show();

    return myapp.exec();

}


运行结果:



解析:
  QPushButton:
    The QPushButton widget provides a push button with a text or pixmap label.


 QPushButton::QPushButton ( const char * text, QWidget * parent=0, const char * name=0 )
  Constructs a push button with a text.The parent and name arguments are sent to the QWidget constructor.


 QObject: 
 The QObject class is the base class of all Qt objects that can deal with signals, slots and events.


  QMetaObject::Connection connect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender, Func1 signal,
                                     const typename QtPrivate::FunctionPointer<Func2>::Object *receiver, Func2 slot,
                                     Qt::ConnectionType type = Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the receiver object.


    Tips:
        *connect(sender,signal,receiver,slot):
             通俗地解释就是,对象A发射信号(这里当用户单击QPushButton时,该按钮就会发射一个click()信号),
             对象B接到信号作出对于处理(这里QApplication接到按钮的clicked()信号,调用用quit()。)
       *宏SIGNAL()和SLOT()是QT语法的一部分




附:
QT官网documentation中给出的connect()例子
QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
                 label,  &QLabel::setText);
This example ensures that the label always displays the current line edit text.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值