简体   繁体   中英

How can I detect the change of value in a QInputDialog?

I want to print the value when changing the value of the dialog called by the getInt method of QInputDialog .

I run the below code, but it is not working:

import sys
from PyQt5.QtCore import Slot
from PyQt5.QtWidgets import QApplication, QInputDialog

@Slot(int)
def int_value_changed(val):
    print(val)

if 'qapp' not in globals():
    qapp = QApplication(sys.argv)

dlg = QInputDialog(None)
dlg.intValueChanged.connect(int_value_changed)

dlg.getInt(None, 'title', 'Type Value', 0)

Functions like getInt are static, which means they create an internal instance of QInputDialog which is not directly accessible from code. If you create your own instance of QInputDialog , you must do all the initialisation yourself and then call exec() (just like an ordinary dialog). As the documentation for QInputDialog shows, this approach is more flexible than using the static functions, since it provides much more scope for customisation.

A roughly equivalent implementation of getInt would be:

import sys
from PyQt5.QtWidgets import QApplication, QInputDialog

def int_value_changed(val):
    print(val)

if QApplication.instance() is None:
    qapp = QApplication(sys.argv)

def getInt(parent, title, label, value=0):
    dlg = QInputDialog(parent)
    dlg.setInputMode(QInputDialog.IntInput)
    dlg.setWindowTitle(title)
    dlg.setLabelText(label)
    dlg.setIntValue(value)
    dlg.intValueChanged.connect(int_value_changed)
    accepted = dlg.exec_() == QInputDialog.Accepted
    dlg.deleteLater()
    return dlg.intValue(), accepted

print(getInt(None, 'Title', 'Type Value', 5))

# print(QInputDialog.getInt(None, 'title', 'Type Value', 5))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM