1

I'm developing a plugin for QGIS that will have a feature open the attribute table with the selected layers.

I split the code into two python files.

This is my code.

First file:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.gui import *
from qgis.core import *
from TabelaAt import TabelaAtributos
from open_attribute_table_dialog import OpenAttributeTableDialog

import resources

import os.path

class OpenAttributeTable:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'OpenAttributeTable_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)


        # Declare instance attributes
        #self.actions = []
        #self.menu = self.tr(u'&OpenAT')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'OpenAttributeTable')
        self.toolbar.setObjectName(u'OpenAttributeTable')
    
    def createToolButton(self, parent, text):
        #criar a ferramenta de botoes
        button = QToolButton(parent)
        button.setObjectName(text)
        button.setToolButtonStyle(Qt.ToolButtonIconOnly)
        button.setPopupMode(QToolButton.MenuButtonPopup)
        parent.addWidget(button)
        return button
    
    def createAction(self, icon_path, text, callback):
        #cria acao
        action = QAction(
            QIcon(icon_path),
            text,
            self.iface.mainWindow())
        action.setCheckable(True)
        action.toggled.connect(callback)
        return action
    
    def initGui(self):
        self.actionCriar = self.createAction(":/plugins/OpenAttributeTable/icon.png", 
                                             u"Abrir Tabela de Atributos",
                                             self.run)
        
        self.tool = TabelaAtributos(self.iface.mapCanvas(), self.actionCriar)
        
        self.selectionButton = self.createToolButton(self.toolbar, u'OpenAttributeTableButton')
        self.selectionButton.addAction(self.actionCriar)
        self.selectionButton.setDefaultAction(self.actionCriar)
        
    
    def openTable(self, b):
        self.actionCriar.setChecked(False)
        self.selectionButton.setDefaultAction(self.selectionButton.sender())
        if b:
            self.iface.mapCanvas().setDefaultAction(self.toolTable)
        else:
            self.iface.mapCanvas().unsetMapTool(self.toolTable)
        
    def unload(self):
        self.iface.mainWindow().removeToolBar(self.toolbar)

    def run(self, b):
        """Run method that performs all the real work"""
        self.selectionButton.setDefaultAction(self.selectionButton.sender())
        if b:
            self.iface.mapCanvas().setMapTool(self.tool)
        else:
            self.iface.mapCanvas().unsetMapTool(self.tool) 

Second file:

from qgis.gui import *
from qgis.core import *
from PyQt4.Qt import *
from qgis.utils import iface
 class TabelaAtributos(QgsMapTool):
    
    def __init__(self, canvas, action):
        self.canvas = canvas
        self.active = False
        QgsMapTool.__init__(self, self.canvas)
        self.setAction(action)
        
    def canvasPressEvent(self, e):
        dv = QgsDualView()
        dv.init( iface.activeLayer(), iface.mapCanvas() )
        dv.setView( QgsDualView.AttributeEditor )
        dv.show()
        
        
    def deactivate(self):
        if self is not None:
            QgsMapTool.deactivate(self)
        
    def activate(self):
        QgsMapTool.activate(self)

I do not know why, but I'm having a mistake.

2
  • whats the mistake? please post the error message as well
    – LaughU
    Jan 4, 2018 at 9:52
  • I probably did not express myself well by using the expression error. Basically I select, a certain area from a layer, but when I click on the plugin button it doesn't open the attributes table. I think there will be some error in my code that causes it not to open the table attributes. Thanks a lot for the help. Jan 4, 2018 at 10:15

1 Answer 1

2

Your code works but this "dialog" close immediately,for fix it need create a custom dialog and add the QgsDualView widget.

Check this example: https://github.com/alfanugraha/lumens_ui/blob/f8e5e209018b4ff0adc1083abb9e61915df508da/dialog_layer_attribute_dualview.py

Example using your code:

from qgis.gui import *
from qgis.core import *
from PyQt4.Qt import *
from PyQt4 import QtGui
from qgis.utils import iface

class DualViewDialog(QDialog):
    def __init__(self, parent = None):
        super(DualViewDialog, self).__init__(parent)
        self.layout = QVBoxLayout(self)

class TabelaAtributos(QgsMapTool):

    def __init__(self, canvas, action):
        self.canvas = canvas
        self.active = False
        QgsMapTool.__init__(self, self.canvas)
        self.setAction(action)

    def canvasPressEvent(self, e):
        dlg = DualViewDialog()
        dv = QgsDualView()
        dv.init( iface.activeLayer(), iface.mapCanvas() )
        dv.setView( QgsDualView.AttributeEditor )
        dlg.layout.addWidget(dv)
        dlg.exec_()         

    def deactivate(self):
        if self is not None:
            QgsMapTool.deactivate(self)

    def activate(self):
        QgsMapTool.activate(self)

Tested using QGIS 2.18.15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.