qt button 右键
时间: 2023-10-14 21:27:23 浏览: 145
要在 Qt Button 上添加右键菜单,可以通过以下步骤实现:
1. 创建自定义按钮类,并在构造函数中添加右键菜单:
```cpp
class MyButton : public QPushButton {
public:
MyButton(QWidget* parent = nullptr) : QPushButton(parent) {
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &MyButton::customContextMenuRequested, this, &MyButton::showContextMenu);
}
private:
void showContextMenu(const QPoint& pos) {
QMenu contextMenu(tr("Context menu"), this);
QAction action1(tr("Action 1"), this);
QAction action2(tr("Action 2"), this);
contextMenu.addAction(&action1);
contextMenu.addAction(&action2);
contextMenu.exec(mapToGlobal(pos));
}
};
```
2. 在主窗口中添加自定义按钮,并在需要的时候设置它的文本、样式等属性:
```cpp
MyButton* button = new MyButton(this);
button->setText(tr("My Button"));
button->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; }");
```
这样,在运行程序并在按钮上右键单击时,就会显示自定义的右键菜单。
阅读全文
相关推荐


















