pyqt5中painter鼠标画线完成后弹出界面包含文本“请输入长度:”以及文本框可输入后关闭的代码
时间: 2024-12-17 21:46:50 浏览: 4
在PyQt5中,你可以使用`QPainter`进行绘图,结合`QDialog`来创建一个简单的交互式界面。以下是一个示例代码,展示如何在鼠标画线结束后弹出一个窗口,让用户输入长度,然后关闭窗口:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPainter, QInputDialog, QLineEdit
from PyQt5.QtGui import QPainterPath
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.init_ui()
def init_ui(self):
self.setGeometry(100, 100, 400, 400)
self.setWindowTitle('Paint and Input')
self.canvas = QWidget()
self.setCentralWidget(self.canvas)
self.path = QPainterPath()
self.connect_mouse_move_and_paint()
def connect_mouse_move_and_paint(self):
self.canvas.mouseMoveEvent = self.on_mouse_move
self.canvas.paintEvent = self.on_paint
def on_mouse_move(self, event):
if event.buttons() & Qt.LeftButton:
self.path.lineTo(event.pos())
self.update_canvas()
def on_paint(self, event):
painter = QPainter(self.canvas)
painter.drawPath(self.path)
def update_canvas(self):
painter = QPainter(self.canvas)
painter.drawPath(self.path)
self.canvas.repaint()
def draw_input_popup(self):
# 创建一个模态对话框
input_dialog = QDialog(self)
input_dialog.setWindowTitle("请输入长度")
layout = QVBoxLayout(input_dialog)
# 添加一个文本输入框
input_line_edit = QLineEdit()
layout.addWidget(input_line_edit)
# 提交按钮
ok_button = QPushButton("确定")
ok_button.clicked.connect(lambda: self.input_popup_closed(input_line_edit.text()))
layout.addWidget(ok_button)
# 关闭按钮
cancel_button = QPushButton("取消")
cancel_button.clicked.connect(input_dialog.reject)
layout.addWidget(cancel_button)
# 设置大小和显示
input_dialog.resize(200, 100)
result = input_dialog.exec_()
# 如果用户点击了确认,获取输入并关闭对话框
if result == QDialog.Accepted:
print(f"输入的长度:{input_line_edit.text()}")
def input_popup_closed(self, length):
self.close_popup()
print(f"已保存长度:{length}")
def close_popup(self):
self.draw_input_popup.hide()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
```
在这个例子中,当用户在窗口上拖动鼠标绘制线条时,`on_paint`函数会被触发,显示绘制的路径。当鼠标绘制结束(例如,松开左键),会调用`draw_input_popup`打开一个对话框让用户输入长度。输入后,对话框会消失,并打印输入的内容。
阅读全文