2015-01-17 40 views
0

我有我想让我的用户选择一个日期,并使用dateedit小部件进入数据库,即时通讯使用委托做这件事,但由于某种原因它也附加时间pyqt4 dateedit delegate不想显示时间

class ProductDelegate(QtSql.QSqlRelationalDelegate): 
    def __init__(self): 
     super().__init__()  

    def createEditor(self, parent, option, index): 

     if index.column() == 3: 
      editor = QtGui.QDateEdit(parent) 
      now = QtCore.QDate.currentDate() 
      editor.setMinimumDate(now) 
      editor.setCalendarPopup(True) 
      return editor 
     else: 
      return QtSql.QSqlRelationalDelegate.createEditor(self, parent, option, index) 

一旦日期被挑剩下的字符串是像'30/01/2015 00:00:00' 我不想在那里的时候?这是什么工作?

enter image description here

+0

如果包括时间,为什么要紧?您可以指定该格式是否以及何时将其显示回用户以符合您的需求。 – jonrsharpe

+0

我已经编辑了这个问题,如果你看一下没有时间使用数据库工具输入,但有附加时间的是如何显示给用户,我该如何指定格式? – Inthuson

回答

2

看起来你可能没有正确设定时,编辑器和/或模型数据格式化值。代表应该看起来像这样:

class ProductDelegate(QtSql.QSqlRelationalDelegate): 
    def createEditor(self, parent, option, index): 
     if index.column() == 3: 
      editor = QtGui.QDateEdit(parent) 
      now = QtCore.QDate.currentDate() 
      editor.setDisplayFormat('yyyy-MM-dd') 
      editor.setMinimumDate(now) 
      editor.setCalendarPopup(True) 
      return editor 
     return super(ProductDelegate, self).createEditor(parent, option, index) 

    def setEditorData(self, editor, index): 
     if index.column() == 3: 
      data = index.data() 
      if not isinstance(data, QtCore.QPyNullVariant): 
       editor.setDate(QtCore.QDate.fromString(data)) 
     else: 
      super(ProductDelegate, self).setEditorData(editor, index) 

    def setModelData(self, editor, model, index): 
     if index.column() == 3: 
      value = editor.date().toString('yyyy-MM-dd') 
      model.setData(index, value, QtCore.Qt.EditRole) 
     else: 
      super(ProductDelegate, self).setModelData(editor, model, index) 
+0

编辑器数据的用途是什么? &型号数据? – Inthuson

+0

@Inthuson。他们完全按照他们的名字表明。如果您重新实现'createEditor',则必须重新实现它们,否则代理将无法正常工作。不过,我的示例代码可能有点简单,因为它并不试图说明您正在使用'QSqlRelationalDelegate'的事实。但是,至少可以解决日期格式问题 - 您是否尝试过? – ekhumoro

+0

Nope,在setEditorData中得到一个错误/:'.py“,第41行 editor.setDate(QtCore.QDate.fromString(index.data())) TypeError:参数不匹配任何重载调用: QDate。 fromString(str,Qt.DateFormat format = Qt.TextDate):参数1有意外的类型'QPyNullVariant' QDate.fromString(str,str):参数1有意外的类型'QPyNullVariant''' – Inthuson