Qt:连接信号和插槽 [英] Qt: Connecting signals and slots
问题描述
我有一个MainWindow包含一个自定义小部件与QTextEdit。
我想在MainWindow和QTextEdit之间创建一个信号/槽。
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.
在MainWindow中有:
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?
推荐答案
为什么麻烦 - 让Qt做所有的魔法:)只需命名你的槽(在mainWindow中)就像这样:
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>);
完成了。更多信息: http://doc.qt.io/qt-5/qmetaobject .html#connectSlotsByName
important:对象名称部分表示对象的名称 - 而不是变量名称。如果你在QtDesigner中设计你的窗口,应该设置(在ui.setupUi方法中)。如果不是 - 手动设置(通过调用 setObjectName
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
只需注意你的槽中的参数数量。这里是我做的:我只是复制信号原型(从头或文档 - 例如: http://doc.qt.io/qt-5/qabstractitemmodel.html#dataChanged - 手表再次为::和方法名[某种类型unbreakable-zerowidth-space] - 只存在当复制从v5.x doc)之间的奇怪的空格,并用 on_objectName _
。这样可以确保您的插槽可以连接到信号
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
这篇关于Qt:连接信号和插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!