Dadep Dadep - 26 days ago 10
Python Question

PyQt open a subwindow with table

I would like to create a window with a button "ruban" and when I click on this button it open a new window with a table containing the "data".
My problem is when i run it, and i click on the button it doesn't appear anything....
Thanks a lot for any help !

#!/usr/bin/env python
# -*- coding: utf-8 -*-



import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *

data = {'col1':['1','2','3'], 'col2':['4','5','6'], 'col3':['7','8','9']}

class Window (QtGui.QMainWindow):

def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("Machine de Turing")
#self.setWindowIcon(QtGui.QIcon('logo.png'))

self.home()

def home(self):

btn1 = QtGui.QPushButton("Ruban", self)
btn1.clicked.connect(self.edit_ruban)
btn1.resize(btn1.sizeHint())

self.show()


def edit_ruban(self):

table = MyTable(self, data, 5, 3)
table.show()


class MyTable(QTableWidget):
def __init__(self, data, *args):
QTableWidget.__init__(self, *args)
self.data = data
self.setmydata()
self.resizeColumnsToContents()
self.resizeRowsToContents()

def setmydata(self):

horHeaders = []
for n, key in enumerate(sorted(self.data.keys())):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)



def run():
app = QtGui.QApplication(sys.argv)
GUI=Window()
sys.exit(app.exec_())

run()

Answer

You have the wrong arguments in call to MyTable.__init__.
It's not clear why you add self as the first arg. Python provides implicit self so it's data that must go first.
If you intended to provide parent window for MyTable it must go last, see the signature QTableWidget::QTableWidget ( int rows, int columns, QWidget * parent = 0 ),
so the call would loo like this:

table = MyTable(data, 5, 3, self)

But MyTable by default will be emdedded into Window Apparently that's not you want. To avoid embedding either omit parent argument and save a reference to the newly created table

def edit_ruban(self):
  table = MyTable(data, 5, 3) # no parent provided
  table.show()
  self.table = table # this prevents the garbage collector
                     # from deleting the new table

or better set window flags to Qt.Window

def edit_ruban(self):
  table = MyTable(data, 5, 3, self)
  table.setWindowFlags(table.windowFlags() | Qt.Window)
  table.show()
Comments