1

I am creating a Plugin for QGIS 3.10 and have made a (big?) mistake. I started by creating the whole GUI in Qt Designer and the corresponding code in Qt Creator with C++. Now I have realized that I need that code in Python to use it in QGIS. I am completely lost now, cause I need to finish this project soon for my studies. As far as I understand, I need to rewrite my plugin from C++ to python now. If there is an other way, i would take that too.

Until now I only managed to use my GUI for the python plugin. enter image description here

here is a part of my original programm code from "mainwindow.h"

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }

QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_tabWidget_currentChanged(int index);

    void on_pushButton_schliessen_clicked();

    void on_pushButton_speichern_clicked();

    void on_button_suchen_clicked();


    void on_pushButton_loeschen_clicked();

private:
    Ui::MainWindow *ui;

};
#endif // MAINWINDOW_H

and my "mainwindow.cpp"

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QApplication>

#include <QSqlDatabase>
#include <QSqlDriver>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
#include <QVariant>
#include <QMessageBox>

QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");

QString suche;
QVariant null;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    db.setHostName("myHost");
    db.setDatabaseName("myDatabase");
    db.setUserName("myUser");
    db.setPassword("myPassword");

    if(db.open())
    {
        qDebug() <<"Database opened" ;
        db.close();
    }
    else
    {
        qDebug() <<"Database couldnt be opened: " + db.lastError().text();
        exit(1);
    }

}

MainWindow::~MainWindow()
{

    delete ui;
}

void MainWindow::on_tabWidget_currentChanged(int index)
{

}

void MainWindow::on_pushButton_schliessen_clicked() //close
{
    close();
}

void MainWindow::on_pushButton_speichern_clicked() //save Database changes
{
    db.open();
    suche = ui->edit_b_nr_lon->text();
    q.prepare("SELECT * FROM myTable WHERE id=:id");
    q.bindValue(":id", suche);
    q.exec();

See as you could see, i am developing a GUI for working with a Database. The problem now is that I don't know how to addres these buttons, input fields, etc. in the .py files shown below.

program_dialog.py

import os

from qgis.PyQt import uic
from qgis.PyQt import QtWidgets

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'baumkataster_dialog_base.ui'))


class BaumkatasterDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(BaumkatasterDialog, self).__init__(parent)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

and program.py

class Baumkataster:
    """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',
            'Baumkataster_{}.qm'.format(locale))

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

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Baumkataster')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Baumkataster', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToDatabaseMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/baumkataster/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u''),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginDatabaseMenu(
                self.tr(u'&Baumkataster'),
                action)
            self.iface.removeToolBarIcon(action)

    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = BaumkatasterDialog()

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            pass
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

these 2 documents where build by the QGIS Plugin Builder. Like i said, i already managed to put my qt creator ui in the corresponding .ui for the .py files.

Now i need some help on how to adress anything from my .ui in the .py.

i would be a good start to get my "pushButton_suchen" to make a console output in QGIS. like "print ("Some output")"

2
  • Did you work through - qgistutorials.com/en/docs/3/building_a_python_plugin.html - before you started?
    – Ian Turton
    Commented Feb 24, 2021 at 11:37
  • yea but a few month ago. then i started to work on my plugin. somehow i managed to completely misunderstand somtething and made my programm in qt with c++. i tried create a new plugin but even there, i am not able adress the GUI elements...
    – sagalo1
    Commented Feb 24, 2021 at 11:41

1 Answer 1

5

you should connect all your buttons to functions before showing the dialog. you can use the function myFunction_suchen to print something for the beginning...:

    if self.first_start == True:
        self.first_start = False
        self.dlg = BaumkatasterDialog()

    # Signale und Slots verknuepfen
    self.dlg.pushButton_schliessen.clicked.connect(self.myFunction_schliessen)
    self.dlg.pushButton_suchen.clicked.connect(self.myFunction_suchen)
    self.dlg.listWidget_Listsomething.doubleClicked.connect(self.doSomething_with the_list_item)
    # and so on
    
   # show the dialog
    self.dlg.show()
1
  • Finally, i get some sort of output. Thanks a lot!!! I hope i get the rest now on my own
    – sagalo1
    Commented Feb 24, 2021 at 13:19

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.