2015-01-17 47 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