qt5在收到信号后新建一个按钮,右键按钮会弹出菜单,一个为连接一个为断开,点击连接会发送按钮的属性到连接函数
时间: 2023-11-27 11:53:33 浏览: 64
初学QT对话框,一个按钮的实现,目的是学着QT的信号和槽,还有使用QTCreator结合QT 设计器的方法
4星 · 用户满意度95%
可以按照以下步骤来实现:
1. 在信号的槽函数中,新建一个按钮并设置其属性:
```cpp
void MyClass::onSignalReceived()
{
QPushButton *newButton = new QPushButton(this);
newButton->setText("New Button");
newButton->setObjectName("myButton"); // 设置对象名为 myButton
connect(newButton, SIGNAL(clicked()), this, SLOT(onButtonClicked()));
}
```
2. 在槽函数中创建一个右键菜单,并将连接和断开操作添加到菜单中:
```cpp
void MyClass::onButtonClicked()
{
QPushButton *button = qobject_cast<QPushButton*>(sender()); // 获取触发信号的按钮
QMenu *menu = new QMenu(this);
QAction *connectAction = new QAction("Connect", this);
QAction *disconnectAction = new QAction("Disconnect", this);
menu->addAction(connectAction);
menu->addAction(disconnectAction);
connect(connectAction, SIGNAL(triggered()), this, SLOT(onConnectClicked()));
connect(disconnectAction, SIGNAL(triggered()), this, SLOT(onDisconnectClicked()));
menu->exec(button->mapToGlobal(QPoint(0, button->height()))); // 显示菜单
}
```
3. 实现连接和断开操作的槽函数,并在其中获取按钮的属性:
```cpp
void MyClass::onConnectClicked()
{
QAction *action = qobject_cast<QAction*>(sender());
QMenu *menu = qobject_cast<QMenu*>(action->parent());
QPushButton *button = qobject_cast<QPushButton*>(menu->parent());
QString buttonName = button->objectName(); // 获取按钮的对象名
// 进行连接操作
}
void MyClass::onDisconnectClicked()
{
QAction *action = qobject_cast<QAction*>(sender());
QMenu *menu = qobject_cast<QMenu*>(action->parent());
QPushButton *button = qobject_cast<QPushButton*>(menu->parent());
QString buttonName = button->objectName(); // 获取按钮的对象名
// 进行断开操作
}
```
阅读全文