Qt: Connecting signals and slots

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 08:37:45

问题


I have a MainWindow that contains a custom widget with a QTextEdit in it. I would like to create a signal/slot between the MainWindow and the QTextEdit.

In MainWindow I have:

QObject::connect(ui->Header,
        SIGNAL(ui->Header->getTextWidget()->textChanged()),
        this, // this : MainWindow
        SLOT(headerUpdated())); // Function of MainWindow

But this does not work. Is it even possible to create such signal/slot combination?


回答1:


why bother - let Qt do all the magic :) Just name your slot (in the mainWindow) like that:

void on_<object name>_<signal name>(<signal parameters>);

And you're done. More info here: http://doc.qt.io/qt-5/qmetaobject.html#connectSlotsByName important: "object name" part means name of the object - not variable name. If you design your window in QtDesigner it should be set (in ui.setupUi method). if not - set it manually (by calling setObjectName

Just watch out for number of arguments in your slot. Here's what I do: I simply copy the signal prototype (from from header or the doc - eg: http://doc.qt.io/qt-5/qabstractitemmodel.html#dataChanged - watch out again for the weird whitespace between "::" and method name [some kind of an unbreakable-zerowidth-space] - only present when copying from v5.x doc), and prepend it with on_objectName_. That guarantees, that your slot will be ok to connect it to the signal



来源:https://stackoverflow.com/questions/28190445/qt-connecting-signals-and-slots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!