Logo Search packages:      
Sourcecode: qt4-x11 version File versions

bool QObject::connect ( const QObject sender,
const char *  signal,
const QObject receiver,
const char *  method,
Qt::ConnectionType  type = Qt::AutoConnection 
) [static, inherited]

Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns true if the connection succeeds; otherwise returns false.

You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:

        QLabel *label = new QLabel;
        QScrollBar *scrollBar = new QScrollBar;
        QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
                         label,  SLOT(setNum(int)));

This example ensures that the label always displays the current scroll bar value. Note that the signal and slots parameters must not contain any variable names, only the type. E.g. the following would not work and return false:

        // WRONG
        QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
                         label, SLOT(setNum(int value)));

A signal can also be connected to another signal:

        class MyWidget : public QWidget
        {
            Q_OBJECT

        public:
            MyWidget();

        signals:
            void buttonClicked();

        private:
            QPushButton *myButton;
        };

        MyWidget::MyWidget()
        {
            myButton = new QPushButton(this);
            connect(myButton, SIGNAL(clicked()),
                    this, SIGNAL(buttonClicked()));
        }

In this example, the MyWidget constructor relays a signal from a private member variable, and makes it available under a name that relates to MyWidget.

A signal can be connected to many slots and signals. Many signals can be connected to one slot.

If a signal is connected to several slots, the slots are activated in an arbitrary order when the signal is emitted.

The function returns true if it successfully connects the signal to the slot. It will return false if it cannot create the connection, for example, if QObject is unable to verify the existence of either signal or method, or if their signatures aren't compatible.

A signal is emitted for every connection you make, so if you duplicate a connection, two signals will be emitted. You can always break a connection using disconnect().

The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message

        QObject::connect: Cannot queue arguments of type 'MyType'
        (Make sure 'MyType' is registed using qRegisterMetaType().)

call qRegisterMetaType() to register the data type before you establish the connection.

See also:
disconnect(), sender(), qRegisterMetaType()

Definition at line 2368 of file qobject.cpp.

References QMetaMethod::attributes(), QMetaObject::checkConnectArgs(), QMetaObject::className(), QMetaObject::connect(), QObject::connectNotify(), QByteArray::constData(), QMetaObject::indexOfSignal(), QMetaObject::indexOfSlot(), QMetaObject::method(), QMetaObject::normalizedSignature(), QMetaMethod::parameterTypes(), and QByteArray::prepend().

Referenced by QMenuBar::actionEvent(), QMenu::actionEvent(), QToolButton::actionEvent(), QObjectCleanupHandler::add(), Q3ActionGroup::add(), QToolBar::addAction(), QMenuBar::addAction(), QMenu::addAction(), QActionGroup::addAction(), Q3MainWindow::addDockWindow(), QFileSystemWatcher::addPaths(), Q3ActionGroup::addTo(), Q3Action::addTo(), QMainWindow::addToolBar(), QtWindowListMenu::addWindow(), QWorkspace::addWindow(), Q3Ftp::checkConnection(), Q3TextEdit::checkOptimMode(), Q3Signal::connect(), QDBusConnection::connectToBus(), Q3Socket::connectToHost(), QProxyModel::connectToModel(), Q3TextEdit::contentsContextMenuEvent(), Q3ListView::contentsMouseMoveEvent(), Q3UrlOperator::copy(), QFormBuilder::createConnections(), Q3MainWindow::createDockWindowMenu(), Q3CheckTableItem::createEditor(), Q3ComboTableItem::createEditor(), QUndoStack::createRedoAction(), QUndoGroup::createRedoAction(), QUndoStack::createUndoAction(), QUndoGroup::createUndoAction(), Q3IconView::doAutoScroll(), Q3ToolBar::event(), QExtensionFactory::extension(), Q3UrlOperator::getNetworkProtocol(), Q3FileDialog::init(), Q3DateEdit::init(), Q3DateTimeEdit::init(), Q3TimeEdit::init(), Q3DataTable::init(), Q3Table::init(), QComboBox::insertItem(), QToolBox::insertItem(), QComboBox::insertItems(), QMainWindow::insertToolBar(), Q3Process::launch(), QTcpServer::listen(), QSvgRenderer::load(), QHostInfo::lookupHost(), Q3MainWindow::menuAboutToShow(), Q3ListBox::mouseMoveEvent(), QDateTimeEdit::mousePressEvent(), QAssistantClient::openAssistant(), Q3Http::operationGet(), Q3Http::operationPut(), Q3ComboBox::popup(), Q3ActionGroup::Q3ActionGroup(), Q3ComboBox::Q3ComboBox(), Q3IconView::Q3IconView(), Q3ListBox::Q3ListBox(), Q3NetworkOperation::Q3NetworkOperation(), Q3NetworkProtocol::Q3NetworkProtocol(), Q3ScrollView::Q3ScrollView(), Q3TabDialog::Q3TabDialog(), Q3Wizard::Q3Wizard(), QAssistantClient::QAssistantClient(), QCalendarWidget::QCalendarWidget(), QDBusAbstractInterface::QDBusAbstractInterface(), QDBusConnectionInterface::QDBusConnectionInterface(), QErrorMessage::QErrorMessage(), QFontComboBox::QFontComboBox(), QFontDialog::QFontDialog(), QFtp::QFtp(), QItemSelectionModel::QItemSelectionModel(), QMovie::QMovie(), QPageSetupDialog::QPageSetupDialog(), QShortcut::QShortcut(), QSortFilterProxyModel::QSortFilterProxyModel(), QStackedWidget::QStackedWidget(), QSvgWidget::QSvgWidget(), QTreeWidget::QTreeWidget(), QtWindowListMenu::QtWindowListMenu(), QAbstractTextDocumentLayout::registerHandler(), QWidgetAction::requestWidget(), QToolBar::resizeEvent(), QUndoGroup::setActiveStack(), Q3Canvas::setAdvancePeriod(), Q3TabDialog::setApplyButton(), QDBusAbstractAdaptor::setAutoRelaySignals(), QProgressDialog::setCancelButton(), Q3ProgressDialog::setCancelButton(), Q3TabDialog::setCancelButton(), Q3CanvasView::setCanvas(), Q3ListView::setColumnWidth(), QLineEdit::setCompleter(), Q3TabDialog::setDefaultButton(), Q3MainWindow::setDockEnabled(), QSyntaxHighlighter::setDocument(), QUndoView::setGroup(), QTreeView::setHeader(), Q3TabDialog::setHelpButton(), QTableView::setHorizontalHeader(), QAbstractItemView::setItemDelegate(), QDataWidgetMapper::setItemDelegate(), QAbstractItemView::setItemDelegateForColumn(), QAbstractItemView::setItemDelegateForRow(), Q3ComboBox::setLineEdit(), QAbstractSpinBox::setLineEdit(), QComboBox::setLineEdit(), Q3ComboBox::setListBox(), QSignalMapper::setMapping(), QPushButton::setMenu(), QComboBox::setModel(), QHeaderView::setModel(), QTreeView::setModel(), QDataWidgetMapper::setModel(), QAbstractItemView::setModel(), QLabel::setMovie(), Q3TabDialog::setOkButton(), QCompleter::setPopup(), QGraphicsView::setScene(), QAbstractItemView::setSelectionModel(), QTreeView::setSelectionModel(), Q3DataTable::setSize(), Q3ServerSocket::setSocket(), QTcpServer::setSocketDescriptor(), QSortFilterProxyModel::setSourceModel(), Q3Dns::setStartQueryTimer(), Q3MainWindow::setStatusBar(), QTabWidget::setTabBar(), QGraphicsItemAnimation::setTimeLine(), setup(), Q3Canvas::setUpdatePeriod(), Q3NetworkProtocol::setUrl(), QDesktopServices::setUrlHandler(), QTableView::setVerticalHeader(), QStatusBar::showMessage(), Q3DataTable::sliderReleased(), and Q3Process::start().

{
    {
        const void *cbdata[] = { sender, signal, receiver, method, &type };
        if (QInternal::activateCallbacks(QInternal::ConnectCallback, (void **) cbdata))
            return true;
    }

#ifndef QT_NO_DEBUG
    bool warnCompat = true;
#endif
    if (type == Qt::AutoCompatConnection) {
        type = Qt::AutoConnection;
#ifndef QT_NO_DEBUG
        warnCompat = false;
#endif
    }

    if (sender == 0 || receiver == 0 || signal == 0 || method == 0) {
        qWarning("QObject::connect: Cannot connect %s::%s to %s::%s",
                 sender ? sender->metaObject()->className() : "(null)",
                 (signal && *signal) ? signal+1 : "(null)",
                 receiver ? receiver->metaObject()->className() : "(null)",
                 (method && *method) ? method+1 : "(null)");
        return false;
    }
    QByteArray tmp_signal_name;

    if (!check_signal_macro(sender, signal, "connect", "bind"))
        return false;
    const QMetaObject *smeta = sender->metaObject();
    ++signal; //skip code
    int signal_index = smeta->indexOfSignal(signal);
    if (signal_index < 0) {
        // check for normalized signatures
        tmp_signal_name = QMetaObject::normalizedSignature(signal).prepend(*(signal - 1));
        signal = tmp_signal_name.constData() + 1;
        signal_index = smeta->indexOfSignal(signal);
        if (signal_index < 0) {
            err_method_notfound(QSIGNAL_CODE, sender, signal, "connect");
            err_info_about_objects("connect", sender, receiver);
            return false;
        }
    }

    QByteArray tmp_method_name;
    int membcode = method[0] - '0';

    if (!check_method_code(membcode, receiver, method, "connect"))
        return false;
    ++method; // skip code

    const QMetaObject *rmeta = receiver->metaObject();
    int method_index = -1;
    switch (membcode) {
    case QSLOT_CODE:
        method_index = rmeta->indexOfSlot(method);
        break;
    case QSIGNAL_CODE:
        method_index = rmeta->indexOfSignal(method);
        break;
    }
    if (method_index < 0) {
        // check for normalized methods
        tmp_method_name = QMetaObject::normalizedSignature(method);
        method = tmp_method_name.constData();
        switch (membcode) {
        case QSLOT_CODE:
            method_index = rmeta->indexOfSlot(method);
            break;
        case QSIGNAL_CODE:
            method_index = rmeta->indexOfSignal(method);
            break;
        }
    }

    if (method_index < 0) {
        err_method_notfound(membcode, receiver, method, "connect");
        err_info_about_objects("connect", sender, receiver);
        return false;
    }
    if (!QMetaObject::checkConnectArgs(signal, method)) {
        qWarning("QObject::connect: Incompatible sender/receiver arguments"
                 "\n\t%s::%s --> %s::%s",
                 sender->metaObject()->className(), signal,
                 receiver->metaObject()->className(), method);
        return false;
    }

    int *types = 0;
    if (type == Qt::QueuedConnection
            && !(types = ::queuedConnectionTypes(smeta->method(signal_index).parameterTypes())))
        return false;

#ifndef QT_NO_DEBUG
    {
        QMetaMethod smethod = smeta->method(signal_index);
        QMetaMethod rmethod = rmeta->method(method_index);
        if (warnCompat) {
            if(smethod.attributes() & QMetaMethod::Compatibility) {
                if (!(rmethod.attributes() & QMetaMethod::Compatibility))
                    qWarning("QObject::connect: Connecting from COMPAT signal (%s::%s)", smeta->className(), signal);
            } else if(rmethod.attributes() & QMetaMethod::Compatibility && membcode != QSIGNAL_CODE) {
                qWarning("QObject::connect: Connecting from %s::%s to COMPAT slot (%s::%s)",
                         smeta->className(), signal, rmeta->className(), method);
            }
        }
    }
#endif
    QMetaObject::connect(sender, signal_index, receiver, method_index, type, types);
    const_cast<QObject*>(sender)->connectNotify(signal - 1);
    return true;
}


Generated by  Doxygen 1.6.0   Back to index