【问题标题】:Python Pyside2 pause script till user returns a value from a slider or qlineeditPython Pyside2 暂停脚本,直到用户从滑块或 qlineedit 返回值
【发布时间】:2018-09-21 19:50:38
【问题描述】:

是否可以在满足某些条件时暂停 python 脚本,以便用户可以通过弹出窗口输入输入,最好是 pyside2 滑块或 qlineedit,然后在用户给出值后恢复脚本。

我唯一能找到的是 qMessageBox 问题,但我唯一可以输入的选项是 2 个按钮,在这种情况下没有用。

我们将不胜感激任何帮助。

谢谢!!

【问题讨论】:

  • 据我了解,您想要一个自定义 QMessageBox,您可以显示您想要的图像,另一方面,如果它是 QSlider,QMessageBox 应该何时关闭?和 QLineEdit 一样
  • 我不想要 QMessageBox,我发现这是我在 PySide2 中发现的唯一会暂停直到用户返回是或否的东西。就我而言,我希望这种情况发生,但可以使用滑块或 qlinedit
  • 你认为它为什么会暂停?,QMessageBox 没有暂停任何东西,应用程序继续运行但窗口应该冻结,它的作用是下一行代码在保持打开状态时没有运行与暂停不同。解决方案是使用答案中指示的 QDialog ,但我强调应用程序没有被暂停,只是被阻止执行下一行。
  • 是的,对不起,我的 python 术语严重缺乏,我的意思是阻止下一行执行。谢谢eyllanesc

标签: python pyside2


【解决方案1】:

您可以使用 QDialog。 http://pyside.github.io/docs/pyside/PySide/QtGui/QDialog.html

https://wiki.qt.io/Qt_for_Python_Tutorial_SimpleDialog

执行以下操作。

from PySide import QtGui  # from PySide2 import QtWidgets or from qtpy import QtWidgets

dialog = QtGui.QDialog()
lay = QtGui.QFormLayout()
dialog.setLayout(lay)

slider = QtGui.QSlider()
lay.addRow(QtGui.QLabel('Slider'), slider)

... # Accept buttons

ans = dialog.exec_()  # This will block until the dialog closes
# Check if dialog was accepted?

value = slider.value()

... # Continue code.

与 exec_QMessageBox 类似的是这个例子。 https://gist.github.com/tcrowson/8152683242018378a00b

您可能可以使用 QMessageBox 并设置布局以更改外观。

发生了什么事?

Essential PySide 通过运行事件循环来工作。它运行这个无限循环,将事件从队列中取出并处理它们。任何鼠标移动或按钮点击都是一个事件。

app = QApplication([])

app.exec_()  # This is running the event loop until the application closes.
print('here')  # This won't print until the application closes

您可以使用任何小部件手动重现此内容。

app = QApplication([])  # Required may be automatic with IPython

slider = QSlider()  # No Parent
slider.show()

# Slider is not visible until the application processes the slider.show() event
app.processEvents()
while slider.isVisible():  # When user clicks the X on the slider it will hide the slider
    app.processEvents()  # Process events like the mouse moving the slider

print('here')  # This won't print until the Slider closes

... # Continue code script

【讨论】:

  • 使用app.processEvents()很臭,不建议使用processEvents(),GUI应该能处理,不要强行使用。
  • @eyllanesc 正确。我只是在解释脚本中发生的事情。
  • @justengel 读 stackoverflow.com/questions/2150966/… 因为那是不正确的,然后他会尝试使用它并在某个时候爆炸。
  • @justengel 我想给你一个反对意见,while slider.isVisible(): app.processEvents() 不等于 exec_() 无处可见
  • @eyllanesc 我猜问这个问题的人并没有真正运行 GUI。该问题表明他正在运行一个脚本,并且只想暂时显示一个小部件。如果是这种情况,他应该使用 QDialog。应用程序代码只是一个无限循环的例子。
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多