2016-02-25 97 views
1

目前我正在用QT編寫日曆程序。我的主窗口有一個QCalendarWidget,現在我想聽單元格的雙擊事件。我的問題是,我不知道我怎麼能得到一個單元格(它是QCalendarWidget的孩子),所以我可以添加一個事件監聽器。隨着:獲取QCalendarWidget的單元格

calendarWidget.findChildren(QtCore.QObject) 

我可以得到小工具的所有孩子,但我不知道如何識別細胞。你有什麼想法,我可以做到這一點?

+0

您使用的是哪個版本的Qt? – Joseph

+0

哦,對不起,忘了這個 - 我正在使用Qt 4.8 – Cilenco

回答

2

日曆小部件包含QTableView,因此您可以獲取對其的引用並查詢其內容。

下面的演示在桌面上安裝event-filter以獲得雙擊,因爲表的doubleClicked信號被日曆禁用(大概是爲了防止編輯單元格)。

from PyQt4 import QtCore, QtGui 

class Window(QtGui.QWidget): 
    def __init__(self): 
     super(Window, self).__init__() 
     self.calendar = QtGui.QCalendarWidget(self) 
     self.table = self.calendar.findChild(QtGui.QTableView) 
     self.table.viewport().installEventFilter(self) 
     layout = QtGui.QVBoxLayout(self) 
     layout.addWidget(self.calendar) 

    def eventFilter(self, source, event): 
     if (event.type() == QtCore.QEvent.MouseButtonDblClick and 
      source is self.table.viewport()): 
      index = self.table.indexAt(event.pos()) 
      print('row: %s, column: %s, text: %s' % (
        index.row(), index.column(), index.data())) 
     return super(Window, self).eventFilter(source, event) 

if __name__ == '__main__': 

    import sys 
    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.setGeometry(750, 250, 300, 300) 
    window.show() 
    sys.exit(app.exec_()) 
+0

非常感謝你的這個效果很好。你從哪裏得到有關QTable的信息?你有沒有發現QCalendarWidget源代碼? – Cilenco

+0

From:'print(self.calendar.children())'。 – ekhumoro