Wednesday, November 11, 2015

ModelViewTutorial

Study QT: Model/View Tutorial

很久沒碰 Python了,這次接到的任務是 Python + Qt 開發測試工具。一開始從需求清單中,找到了 QColumnView 來做主要的呈現。但接下來的過程中,卻找不太到充足的資料來使用這介面。以下便是學習這題目的資料。

  1. 透過 QT: Model/View Tutorial 了解 model (資料內容本身) 和 view (呈現方式) 彼此是如何運作的。具體內容請參考來源,在此我附上了相對應的 Python code 參考。

    1. ex01_readonly.py
    2. ex02_formatting.py
    3. ex03_changingmode.py
    4. ex04_headers.py
    5. ex05_edit.py
    6. ex06_treeview.py
    7. ex07_selections.py
  2. QColumnView 的最後一欄位,是用來做 preview 功能的。一開始不了解時,一直被為啥多了一個空白欄位感到不解,為移除最後這一欄位花了很多時間,最後看到文件中 previewWidget() 和 updatePreviewWidget signal,才了解最後一欄位的用意。以下為我寫的範例:

    1. ex08_columnview.py
        #!/usr/bin/python
    # -*- coding: utf-8 -*-
    #
    # (c) 2015 RyanYao, http://nienfeng.blogspot.tw/
    #

    import sys
    import os
    from PySide import QtGui, QtCore


    class Example(QtGui.QMainWindow):
        def __init__(self):
            super(Example, self).__init__()
            self.initUI()

        def initUI(self):
            self.model = QtGui.QStandardItemModel()
            self.view = QtGui.QColumnView()
            self.setCentralWidget(self.view)
            self.view.setModel(self.model)
            self.view.updatePreviewWidget.connect(self.previewWidget)

            root = self.model.invisibleRootItem()
            for i in range(3):
                group = QtGui.QStandardItem("Group %d" % i)
                # childs = []
                for j in range(4):
                    child = QtGui.QStandardItem("Child %d-%d" % (i,j))
                    group.appendRow(child)
                root.appendRow(group)
            self.show()

        def previewWidget(self, index):
            print index.row(), index.column()
            hierarchyLevel = 1
            seekRoot = index

            while(seekRoot.parent() != QtCore.QModelIndex()):
                seekRoot = seekRoot.parent()
                hierarchyLevel += 1
            edit = QtGui.QPlainTextEdit()
            edit.appendPlainText("%s, Level %d" % (index.data(), hierarchyLevel))
            self.view.setPreviewWidget(edit);


    def main():
        app = QtGui.QApplication(sys.argv)
        ex = Example()
        sys.exit(app.exec_())


    if __name__ == '__main__':
        main()

No comments: