QDialog设置可拖动
时间: 2023-11-08 11:14:16 浏览: 202
对话框的拖动
5星 · 资源好评率100%
要使QDialog可拖动,可以通过两种方法实现:
方法一:使用setMouseTracking和mousePressEvent
```python
class MyDialog(QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.dragPosition = None
self.setMouseTracking(True)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton and self.dragPosition is not None:
self.move(event.globalPos() - self.dragPosition)
event.accept()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragPosition = None
event.accept()
```
方法二:使用QDialog的setWindowFlags方法
```python
class MyDialog(QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowMinMaxButtonsHint)
```
这里,我们使用了Qt.CustomizeWindowHint标志以自定义对话框的外观,Qt.WindowTitleHint以显示标题栏,并使用Qt.WindowMinMaxButtonsHint以显示最小化和最大化按钮。这样,用户就可以通过拖拽标题栏移动对话框了。
阅读全文