有具体的代码嘛
时间: 2023-09-10 21:15:39 浏览: 114
参考的代码
当然可以给出一些示例代码来帮助您更好地理解:
1. 鼠标事件的实现:
```
void MyWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragging = true;
m_dragPos = event->pos();
}
}
void MyWidget::mouseMoveEvent(QMouseEvent *event)
{
if (m_dragging) {
QPoint newPos = event->pos();
QPoint delta = newPos - m_dragPos;
m_button->move(m_button->pos() + delta);
m_dragPos = newPos;
statusBar()->showMessage(QString("x=%1, y=%2").arg(m_button->x()).arg(m_button->y()));
}
}
void MyWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragging = false;
}
}
```
2. 键盘事件的实现:
```
void MyWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_M && event->modifiers() == Qt::ControlModifier) {
showMaximized();
}
}
```
3. 弹出式菜单的实现:
```
QMenu *menu = new QMenu(this);
QAction *maximizeAction = new QAction(QIcon(":/icons/maximize.png"), tr("最大"), this);
QAction *minimizeAction = new QAction(QIcon(":/icons/minimize.png"), tr("最小"), this);
QAction *normalAction = new QAction(QIcon(":/icons/normal.png"), tr("普通"), this);
menu->addAction(maximizeAction);
menu->addAction(minimizeAction);
menu->addAction(normalAction);
connect(maximizeAction, &QAction::triggered, this, &MyWidget::maximize);
connect(minimizeAction, &QAction::triggered, this, &MyWidget::minimize);
connect(normalAction, &QAction::triggered, this, &MyWidget::normal);
m_button->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_button, &QWidget::customContextMenuRequested, [=](const QPoint &pos){
menu->exec(m_button->mapToGlobal(pos));
});
```
4. 工具栏的实现:
```
QToolBar *toolbar = new QToolBar(this);
toolbar->addAction(maximizeAction);
toolbar->addAction(minimizeAction);
toolbar->addAction(normalAction);
addToolBar(toolbar);
```
5. 双击事件的实现:
```
void MyWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
showMaximized();
} else if (event->button() == Qt::RightButton) {
showNormal();
}
}
```
这些代码仅供参考,具体实现过程还需要根据您的需求和布局进行适当修改。
阅读全文