Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pyside6
#1
I wrote some early Qt code using the designer, and have used tkinter and wxpython almost exclusively since.
I am now in early learning of QT using Pyside6, (finally working on an application where GUI will be exclusively QT).
I'm trying to place a QTableWidget on top of a QMainWindow, and am doing something wrong, but not sure what.
Could use some help.

here's the code I attempted to write:
import sys
from PySide6.QtWidgets import (QApplication, QMainWindow,
        QWidget, QTableWidget, QTableWidgetItem)
from PySide6.QtGui import QPalette, QColor


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowTitle("Table Widget")


class Table(QTableWidget):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)

        self.colors = [("Red", "#FF0000"),
                ("Green", "#00FF00"),
                ("Blue", "#0000FF"),
                ("Black", "#000000"),
                ("White", "#FFFFFF"),
                ("Electric Green", "#41CD52"),
                ("Dark Blue", "#222840"),
                ("Yellow", "#F9E56d")]

        self.table = QTableWidget()

    def get_rgb_from_hex(self, code):
        code_hex = code.replace("#", "")
        rgb = tuple(int(code_hex[i:i+2], 16) for i in (0, 2, 4))
        return QColor.fromRgb(rgb[0], rgb[1], rgb[2])

    def define_table(self):
        self.table.setRowCount(len(self.colors))
        self.table.setColumnCount(len(self.colors[0]) + 1)
        self.table.setHorizontalHeaderLabels(["Name", "Hex Code", "Color"])

        for i, (name, code) in enumerate(self.colors):
            item_name = QTableWidgetItem(name)
            item_code = QTableWidgetItem(code)
            item_color = QTableWidgetItem()
            item_color.setBackground(self.get_rgb_from_hex(code))
            self.table.setItem(i, 0, item_name)
            self.table.setItem(i, 1, item_code)
            self.table.setItem(i, 2, item_color)


def main():
    app = QApplication(sys.argv)

    window = MainWindow()
    table = Table(parent = window)
    table.define_table()
    # window.show()
    table.show()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()
Reply
#2
As you are subclassing QTableWidget I'm not sure why you have
self.table = QTableWidget()
remove that and change all the references to self.table to just self
you probably then need to add a layout or window.setCentralWidget(table)
Reply
#3
Yoriz Wrote:As you are subclassing QTableWidget I'm not sure why you have
I'm not sure either... I just started the tutorial, and somewhat confused.

That fixed the problem with the table being within the window widget, but nor I'm having a table size issue.
I'm pushing myself, and trying to expand on the exercise, but when I make errors, I don't forget how to do it right.
I beleive if properly resized, the table will show properly

At any rate, here's what I have now:
import sys
from PySide6.QtWidgets import (QApplication, QMainWindow,
        QWidget, QTableWidget, QTableWidgetItem, QHeaderView)

from PySide6.QtGui import QPalette, QColor


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowTitle("Table Widget")


class Table(QTableWidget):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)

        self.colors = [("Red", "#FF0000"),
                ("Green", "#00FF00"),
                ("Blue", "#0000FF"),
                ("Black", "#000000"),
                ("White", "#FFFFFF"),
                ("Electric Green", "#41CD52"),
                ("Dark Blue", "#222840"),
                ("Yellow", "#F9E56d")]

    def get_rgb_from_hex(self, code):
        code_hex = code.replace("#", "")
        rgb = tuple(int(code_hex[i:i+2], 16) for i in (0, 2, 4))
        return QColor.fromRgb(rgb[0], rgb[1], rgb[2])

    def define_table(self):
        self.setItemDelegate(self.itemDelegate())
        self.setRowCount(len(self.colors))
        self.setColumnCount(len(self.colors[0]) + 1)
        self.setHorizontalHeaderLabels(["Name", "Hex Code", "Color"])
        
        for i, (name, code) in enumerate(self.colors):
            item_name = QTableWidgetItem(name)
            item_code = QTableWidgetItem(code)
            item_color = QTableWidgetItem()
            item_color.setBackground(self.get_rgb_from_hex(code))
            self.setItem(i, 0, item_name)
            self.setItem(i, 1, item_code)
            self.setItem(i, 2, item_color)

        hh = self.horizontalHeader()
        hh.setSectionResizeMode(QHeaderView.ResizeToContents)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    table = Table(parent=window)
    table.define_table()
    window.show()
    table.show()
    app.exec()


if __name__ == '__main__':
    main()
Reply
#4
try this

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    table = Table(parent=window)
    table.define_table()
    window.setCentralWidget(table)
    window.show()
    #table.show()
    app.exec()
Reply
#5
Thanks Axel_Erfurt and Yoriz,

Always wonderful, and at the same time painful painful when learning something new.

That worked, It would have been some time before I found that method.

Is this statement still used when you have, for example, a screen with many widgets, panels, etc. each related, but somewhat independant of the other?

I have a specific project that I am working on, and it will have several 'panels' (not sure yet of Qt terminology). I suppose I will set one as central, but the others will all be accessable, for related information.

I will say that the documentation is very well done, but knowing how to choose the proper methods and class for the job will take time, trial and error.
Reply
#6
QMainWindow has a central widget. You can make this any kind of widget you like, including a QWidget which is blank. Then you can add a layout manager to the central widget to help you position other widgets within this widget. You can even stack widgets on top of each other. I used this to make a tool ribbon (a tab like interface that uses tool bar buttons in place of tabs).

I only use a QMainWindow when I want a menu and a status bar. I don't use the docking capabilities very often because Qt's docking is not very flexible. Normally I subclass QWidget to make my own window classes. I find this gives me more freedom than using QMainWindow.
Reply
#7
(Nov-28-2022, 02:05 PM)Larz60+ Wrote: Is this statement still used when you have, for example, a screen with many widgets, panels, etc. each related, but somewhat independant of the other?

If you have more widgets use layouts.

I've added some widgets to your code for example

import sys
from PySide6.QtWidgets import (QApplication, QMainWindow,
        QWidget, QTableWidget, QTableWidgetItem, QHeaderView,
        QHBoxLayout, QVBoxLayout, QTextEdit, QSizePolicy)
 
from PySide6.QtGui import QPalette, QColor
 
 
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
 
        self.setWindowTitle("Table Widget")
        self.table = Table()
        self.table.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.table.define_table()
        self.table.itemSelectionChanged.connect(self.get_cell)
        
        # hbox layout
        hbox = QHBoxLayout()
        hbox.addWidget(self.table)
        
        # add textedit right to table
        self.text_edit = QTextEdit(plainText = "Hello World")
        
        hbox.addWidget(self.text_edit)
        
        #vbox layout
        vbox = QVBoxLayout()
        
        # add hbox to vbox
        vbox.addLayout(hbox)
        
        # add textedit below table
        self.another_text_edit = QTextEdit(plainText = "Hello World")
        vbox.addWidget(self.another_text_edit)
        
        # central widget
        central_widget = QWidget()
        central_widget.setLayout(vbox)
        
        self.setCentralWidget(central_widget)
        self.statusBar().showMessage("Ready")
        
    def get_cell(self):
        widget = self.table
        index = widget.selectedItems()[0]
        cell_text = widget.item(index.row(), index.column()).text()
        self.statusBar().showMessage(f"cell text: {cell_text}")
 
 
class Table(QTableWidget):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)
 
        self.colors = [("Red", "#FF0000"),
                ("Green", "#00FF00"),
                ("Blue", "#0000FF"),
                ("Black", "#000000"),
                ("White", "#FFFFFF"),
                ("Electric Green", "#41CD52"),
                ("Dark Blue", "#222840"),
                ("Yellow", "#F9E56d")]
 
    def get_rgb_from_hex(self, code):
        code_hex = code.replace("#", "")
        rgb = tuple(int(code_hex[i:i+2], 16) for i in (0, 2, 4))
        return QColor.fromRgb(rgb[0], rgb[1], rgb[2])
 
    def define_table(self):
        self.setItemDelegate(self.itemDelegate())
        self.setRowCount(len(self.colors))
        self.setColumnCount(len(self.colors[0]) + 1)
        self.setHorizontalHeaderLabels(["Name", "Hex Code", "Color"])
         
        for i, (name, code) in enumerate(self.colors):
            item_name = QTableWidgetItem(name)
            item_code = QTableWidgetItem(code)
            item_color = QTableWidgetItem()
            item_color.setBackground(self.get_rgb_from_hex(code))
            self.setItem(i, 0, item_name)
            self.setItem(i, 1, item_code)
            self.setItem(i, 2, item_color)
 
        hh = self.horizontalHeader()
        hh.setSectionResizeMode(QHeaderView.ResizeToContents)
 
 
def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setGeometry(100, 100, 600, 500)
    window.show()
    app.exec()
 
 
if __name__ == '__main__':
    main()
Reply
#8
Thanks
deanhystad Wrote:I don't use the docking capabilities very often because Qt's docking is not very flexible
I'm not a big fan of docking, wxpython is fairly good in this respect, but never used it much.
I figure that creating a new separate window is better, use it for what you need, and then close it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PySide6 - Connect to DBus signal - Correct syntax Drexel 1 580 Dec-18-2023, 08:03 AM
Last Post: Drexel
  PySide6 Copy and Past from clipboard to QTableWedget zinho 6 1,152 Dec-07-2023, 10:10 PM
Last Post: zinho
Bug [PyQt] Dinamically adding widgets to layout [PySide6] carecavoador 2 1,369 Jun-19-2023, 12:57 PM
Last Post: carecavoador
  PySide6 QFontDialog - bug or just me? PatM 1 1,073 Jan-22-2023, 01:29 PM
Last Post: Axel_Erfurt
  [PySide6] Load ui with UiLoader catlessness 6 8,639 Nov-24-2021, 02:17 PM
Last Post: catlessness

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020