【问题标题】:Is there a way to create an Input dialog in pyqt5 that does not close after clicking ok button有没有办法在 pyqt5 中创建一个输入对话框,单击确定按钮后不会关闭
【发布时间】:2020-03-03 06:33:52
【问题描述】:

有什么方法可以创建一个带有组合框的输入对话框,该组合框在单击确定按钮后不会关闭。 我尝试使用

QInputDialog.setOption(QInputDialog[NoButtons, on=True])

那没用。我尝试使用第二个窗口,但无法正确配置。

另外,我有什么方法可以将 OK 按钮信号用于其他地方的逻辑?

【问题讨论】:

  • 更好地解释自己,因为您的问题不清楚,它也会显示您尝试过的内容,即使它不起作用。
  • 对不起,我马上编辑它..

标签: python pyqt pyqt5 qinputdialog


【解决方案1】:

如果您想使用选项QInputDialog.NoButtons 打开 QInputDialog,您可以这样做:

dg = QInputDialog()
dg.setOption(QInputDialog.NoButtons)
dg.setComboBoxItems(['Item A', 'Item B', 'Item C'])
dg.exec_()

QInputDialog 类的目的是提供一种非常简单方便的方式来获取用户输入,而无需太多自定义空间。 OK 按钮信号始终连接到对话框的accept 插槽。如果您想更改各种信号和插槽的设置,我建议将 QDialog 子类化并构建自己的。这是一个简单的例子,当按下 OK 时窗口不会关闭,而是将当前项目打印到 shell。

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class CustomDialog(QDialog):

    item_selected = pyqtSignal(str)

    def __init__(self, items, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.box = QComboBox()
        self.box.addItems(items)
        btn = QPushButton('Ok')
        btn.clicked.connect(self.ok_pressed)
        vbox = QVBoxLayout(self)
        vbox.addWidget(self.box)
        vbox.addWidget(btn)

    def ok_pressed(self):
        self.item_selected.emit(self.box.currentText())


class Template(QWidget):

    def __init__(self):
        super().__init__()
        dg = CustomDialog(['Item A', 'Item B', 'Item C'], self)
        dg.item_selected[str].connect(self.do_something)
        dg.exec_()

    def do_something(self, item):
        print(item)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = Template()
    gui.show()
    sys.exit(app.exec_())

【讨论】:

  • 太棒了!谢谢!
猜你喜欢
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
相关资源
最近更新 更多