gpt4 book ai didi

c++ - Qt 中两个插件的信号/插槽交互

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:43 25 4
gpt4 key购买 nike

所以基本上我有一个加载两个插件并连接它们的小应用程序。加载后的第一个插件会创建一个没有任何标题的标签,该标签将被添加到主窗口。第二个插件创建一个将添加到菜单的操作。所以我的应用程序只需要加载这些插件并连接它们。连接它们是什么意思?我的意思是标签插件包含一个插槽,它将修改标签的标题,并且 Action 插件声明了一个信号。应用程序应connect Action 插件信号与标签插槽。我不知道该怎么做。我的猜测是,实际上插件类实现是将自定义信号与标准信号(已触发)连接起来。但无论如何,我的应用程序无法按预期工作。如何在我的应用程序中正确连接一个插件的信号和另一个插件的插槽??

这是我的标签插件代码:

#include "LabelInterface.h"

class LabelPlugin : public LabelInterface {

Q_OBJECT
Q_INTERFACES(LabelInterface)

public:
QLabel* label;
QLabel* newLabel();
LabelPlugin() {}
~LabelPlugin() {}

public slots:
void setTextforLabel();
};

#include <QtGui>
#include "LabelPlugin.h"

QLabel* LabelPlugin::newLabel() {

label = new QLabel("");
return label;
}

void LabelPlugin::setTextforLabel() {

label->setText("This plugin works fine");
}

// Exporta plugin-ul
Q_EXPORT_PLUGIN2 (labelplugin,LabelPlugin)

Action 插件:

    #include "ActionInterface.h"

class ActionPlugin : public ActionInterface {

Q_OBJECT
Q_INTERFACES (ActionInterface)

public :
QAction* myAction;
QAction* newAction();

~ActionPlugin () {}
ActionPlugin () {}

public slots:
void send_signal();

signals :
void pushMyAction();
};

#include <QtGui>
#include "ActionPlugin.h"

QAction* ActionPlugin::newAction() {

myAction = new QAction("Show text",this);

return myAction;
}

void ActionPlugin::send_signal() {

qDebug ()<<"Here";

QAction::connect (this,SIGNAL(pushMyAction()),this,SIGNAL(triggered()));
}

Q_EXPORT_PLUGIN2 (actionplugin,ActionPlugin)

在我的应用程序中,我尝试加载我拥有的插件:

   foreach (QString fileName, appDir.entryList(QDir::Files)) {

qDebug()<<QString(fileName);

QPluginLoader pluginLoader(appDir.absoluteFilePath(fileName));

QObject* plugin = pluginLoader.instance();

if (plugin) {

ActionInterface* myAction= qobject_cast<ActionInterface*>(plugin);

if (myAction) {
action_ = myAction;
pluginMenu->addAction(action_->newAction());
}

LabelInterface* myLabel = qobject_cast<LabelInterface*>(plugin);

if (myLabel) {
label_=myLabel;
layout->addWidget(label_->newLabel());
}

if (action_ && label_) {

qDebug()<<"both loaded";

action_->send_signal();
connect(action_, SIGNAL(pushMyAction()),label_, SLOT(setTextforLabel()));
}
else qDebug() << "seems one plugin is not loaded";
}
}

最佳答案

您需要能够从每个插件访问 QObject 实例,以便您可以在连接调用中使用它。我会在您的接口(interface)中添加方法来执行此操作。我见过的一种模式是将接口(interface)转换为 QObject 指针的运算符,例如:

class MyInterface {
public:
virtual operator QObject*() = 0;
};

关于这是否是好的风格,意见可能会有所不同,但它解决了问题(如果您不喜欢运算符,请使用称为 asQObject() 或类似的方法)。

关于c++ - Qt 中两个插件的信号/插槽交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com