1

I need to read some raster data and show their information in a tree widget, but while I use QgsLayerTreeView, it can not shown in my GUI. The last is my code, I want to know where i am wrong

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from qgis.gui import *
from qgis.core import *
import sys
import os


class MyWnd(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.main_widget = QWidget()
        self.tree = QgsLayerTreeView()

        pro = QgsProject.instance()
        pro.read("D:/项目/GUI开发/code/20181030/data2/my_pro.qgs")

        k = 1
        for file in os.listdir(file_folder):
            if file[-3:] == 'tif':
                filename = file_folder + "/" + file
                file_info = QFileInfo(filename)
                base_name = file_info.baseName()

                if k < 10:
                    layer = QgsRasterLayer(filename, base_name)
                    QgsProject.instance().addMapLayer(layer)
                    k = k + 1

        root = QgsProject.instance().layerTreeRoot()
        model = QgsLayerTreeModel(root)
        self.tree.setModel(model)

        self.setCentralWidget(self.tree)
        self.show()
        pro.write()


if __name__ == '__main__':

    file_folder = "D:/项目/GUI开发/code/20181030/data2"
    QgsApplication.setPrefixPath(r"C:\OSGeo4W64", True)
    qgs = QgsApplication([], True)
    qgs.initQgis()
    app = QApplication(sys.argv)
    w = MyWnd()
    sys.exit(app.exec_())
    qgs.exitQgis()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.