Question

I am building a Gui in QtDesigner but i do not understand how i add a "dynamical property": I try to add a QTable Widget but the Header of the Columns are to large (The Text is just 2 letter in the Columns). For Space reasons in my Gui i just need them to be as big as the text is (or let us say 4 letters)

i found the QHeaderView::ResizeToContents method but i do not know how to use it- is there a way to do this in QtDesigner?

I am new to this and i do not know how to change the code behind the Gui...

Was it helpful?

Solution

For PyQt, the main purpose of Qt Designer is to create the main GUI structure of your application. It only allows a subset of the available properties to be modified for any given widget, and it cannot be used to write the application's main logic.

Instead, the idea is to generate a python module from the ui file created by Qt Designer, and then import it into your application where you can do the remaining setup code, connect signals, write all the event handlers, etc.

Let's say you've created a ui file with Qt Designer and named it mainwindow.ui.

You would then generate the python module like this:

pyuic4 -o mainwindow_ui.py mainwindow.ui

Next, you would write a separate main.py script that imports the GUI classes from the generated module, and creates instances of them as needed.

So your main.py would look something like this:

from PyQt4 import QtCore, QtGui
from mainwindow_ui import Ui_MainWindow

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        header = self.tableWidget.horizontalHeader()
        header.setResizeMode(QtGui.QHeaderView.ResizeToContents)
        ...

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

The base-class here must be same as the top-level widget in Qt Designer (i.e. usually either QMainWindow, QDialog, or QWidget). Also, the objectName property of the top-level widget is used to generate the classname of the imported GUI class (with "Ui_" prepended to it). The example above assumes this was set to "MainWindow".

The objectName properties of all the other widgets will become attributes of the MainWindow class, so that they can be accessed easily in the rest of your code. Because of this, it's important that you always set the objectName properties to descriptive names (i.e. not "pushButton_1", "pushButton_2", etc).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top