我有一个QTreeWidget与3列,只有第3列应该有一个双验证器。我的问题是,它在某种程度上是有效的;QLineEdit不会在100处停止,它只是继续前进。
我错过了什么;使它不让用户输入任何大于100的东西,而仍然编辑lineEdit?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Delegate(QStyledItemDelegate):
'Changes number of decimal places in gas analysis self.chosen table'
def __init__(self, decimals, parent=None):
super().__init__(parent)
self.nDecimals = decimals
def createEditor(self, parent, option, index):
editor = QLineEdit(parent)
editor.setValidator(QDoubleValidator(0,100, 15))
return editor
def setEditorData(self, editor, index):
if index.column() == 2 and index.data() is not None:
editor.setText(str(float(index.data())))
class Widget(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent=None)
self.tree_widget = QTreeWidget()
self.tree_widget.setItemDelegate(Delegate(self.tree_widget))
self.tree_widget.setHeaderLabels(["Value1", "Value2", "Value3"])
self.setCentralWidget(self.tree_widget)
for vals in [("h", "20.0", "40.0"), ("k", "25.0", "50.0")]:
it = QTreeWidgetItem(vals)
it.setFlags(it.flags()| Qt.ItemIsEditable)
self.tree_widget.addTopLevelItem(it)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
QDoubleValidator只尝试验证用户输入的文本,如果它不满足要求,那么信息将不会被保存,这就是在您的情况下观察到的。如果您想在您的特定情况下定义您希望用户使用的值,那么最好使用QDoubleSpinBox作为编辑器:
class Delegate(QStyledItemDelegate):
def __init__(self, decimals, parent=None):
super().__init__(parent)
self.nDecimals = decimals
def createEditor(self, parent, option, index):
editor = QDoubleSpinBox(
parent, minimum=0, maximum=100.0, decimals=self.nDecimals
)
return editor
def setEditorData(self, editor, index):
if index.data() is not None:
try:
value = float(index.data())
except Exception as e:
print("error", e)
else:
editor.setValue(value)
class Widget(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent=None)
self.tree_widget = QTreeWidget()
self.tree_widget.setHeaderLabels(["Value1", "Value2", "Value3"])
self.tree_widget.setItemDelegateForColumn(2, Delegate(15, self.tree_widget))
self.setCentralWidget(self.tree_widget)
for vals in [("h", "20.0", "40.0"), ("k", "25.0", "50.0")]:
it = QTreeWidgetItem(vals)
it.setFlags(it.flags() | Qt.ItemIsEditable)
self.tree_widget.addTopLevelItem(it)
注意:我已经修改了列选择,因为在OP的初始实现中,在所有列中使用了相同的编辑器,这显然与它的相同要求相矛盾,所以我使用的不是setItemDelegate(),而是setItemDelegateForColumn()。