How to add dropdown menu to QMessageBox? - python

After looking at some code I found on stackoverflow, I was able to find a way to add a table to a QmessageBox. Now that I have done that, I would like to place a drop down menu in the top right of the QmessageBox and I cannot figure out a way to do that (if it even is possible).
Here is my edited code:
from PyQt4.QtGui import *
from PyQt4.Qt import *
import sys
class MyMessageBox(QMessageBox):
def __init__(self):
QMessageBox.__init__(self)
self.setSizeGripEnabled (True)
self.setWindowTitle('Get Parent Script')
self.setIcon(self.Question)
#self.setText("Hello MessageBox")
self.addButton("Select", QMessageBox.ActionRole)
self.setStandardButtons(QMessageBox.Cancel)
#self.addWidget(QInputDialog())
self.addTableWidget (self)
currentClick = self.exec_()
def addTableWidget (self, parentItem) :
self.l = QVBoxLayout()
self.tableWidget = QTableWidget(parentItem)
self.tableWidget.setObjectName ('tableWidget')
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(2)
self.tableWidget.setHorizontalHeaderLabels(QString("Nuke Script;File Modification Time;User").split(";"))
header = self.tableWidget.horizontalHeader()
header.setResizeMode(0, QHeaderView.ResizeToContents)
header.setResizeMode(1, QHeaderView.Stretch)
header.setResizeMode(2, QHeaderView.Stretch)
stringlist = {u'/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp':u'user1', u'/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp/hello': u'user2'}
row = 0
for key, value in stringlist.iteritems():
print key, value
nameitem = QTableWidgetItem(str(key))
codeitem = QTableWidgetItem(str(value))
self.tableWidget.setItem(row,0,nameitem)
self.tableWidget.setItem(row,1,codeitem)
row +=1
self.tableWidget.resize(1000, 170)
self.l.addWidget(self.tableWidget)
self.setLayout(self.l)
def event(self, e):
result = QMessageBox.event(self, e)
self.setMinimumWidth(0)
self.setMaximumWidth(16777215)
self.setMinimumHeight(0)
self.setMaximumHeight(16777215)
self.setSizePolicy(
QSizePolicy.Expanding,
QSizePolicy.Expanding
)
self.resize(1000, 300)
return result
def run_cli():
#app = QtWidgets.QApplication(sys.argv)
app = QApplication(sys.argv)
MyMessageBox()
if __name__ == '__main__':
run_cli()

In your case it is not optimal to use QMessageBox since I involve unnecessary work because this widget already has a predefined layout, instead you can create a widget based on a QDialog:
from PyQt4 import QtCore, QtGui
class Dialog(QtGui.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
label = QtGui.QLabel("Text")
combo = QtGui.QComboBox()
combo.addItems(["option1", "option2", "option3"])
self.tableWidget = QtGui.QTableWidget(2, 3)
self.tableWidget.setHorizontalHeaderLabels(
QtCore.QString("Nuke Script;File Modification Time;User").split(";")
)
header = self.tableWidget.horizontalHeader()
header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents)
header.setResizeMode(1, QtGui.QHeaderView.Stretch)
header.setResizeMode(2, QtGui.QHeaderView.Stretch)
stringlist = {
u"/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp": u"user1",
u"/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp/hello": u"user2",
}
for row, (key, value) in enumerate(stringlist.iteritems()):
nameitem = QtGui.QTableWidgetItem(str(key))
codeitem = QtGui.QTableWidgetItem(str(value))
self.tableWidget.setItem(row, 0, nameitem)
self.tableWidget.setItem(row, 1, codeitem)
box = QtGui.QDialogButtonBox(
QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
centerButtons=True,
)
box.accepted.connect(self.accept)
box.rejected.connect(self.reject)
lay = QtGui.QGridLayout(self)
lay.addWidget(label, 0, 0)
lay.addWidget(combo, 0, 1)
lay.addWidget(self.tableWidget, 1, 0, 1, 2)
lay.addWidget(box, 2, 0, 1, 2)
self.resize(640, 240)
def run_cli():
import sys
app = QtGui.QApplication(sys.argv)
w = Dialog()
w.exec_()
if __name__ == "__main__":
run_cli()

Related

pyside2 how to query and create and delete dynamic widget

layout
layout (1)
QlineEdit
Qpushbutton
layout (2)
QlineEdit
Qpushbutton
Qpushbutton (3)
I try to create and delete layout(1,2) in layout.
it's work real time. layout(1,2) are dynamic number (1,2,3,~~)
Qpushbutton click -> parent layout and widget delete
and query text in QlineEdit
my test code --
#-*- coding:utf-8 -*-
import maya.cmds as mc
import os
import pprint
from PySide2 import QtWidgets, QtCore, QtGui
class PreferenceUI(QtWidgets.QDialog):
def __init__(self):
super(PreferenceUI, self).__init__()
self.setWindowTitle("preference")
self.create_widgets()
self.create_layouts()
self.create_connections()
self.load_department()
def create_widgets(self):
self.departmentNameLine = QtWidgets.QLineEdit()
self.departmentNameLine.setFixedSize(100,20)
self.departmentPathLine = QtWidgets.QLineEdit()
self.departmentMinusBtn = QtWidgets.QPushButton("-")
self.departmentMinusBtn.setFixedSize(20,20)
self.departmentPlusBtn = QtWidgets.QPushButton("+")
self.sysAppendWidget = QtWidgets.QTextEdit()
def create_layouts(self):
self.mainLayout = QtWidgets.QFormLayout(self)
self.departmentLayout = QtWidgets.QVBoxLayout()
self.departmentLastLayout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(self.departmentLastLayout)
self.departmentLayout.addWidget(self.departmentPlusBtn)
self.mainLayout.addRow("department :", self.departmentLayout)
self.mainLayout.insertRow(self.mainLayout.count()-1, "sys.path.append :", self.sysAppendWidget)
def create_connections(self):
pass
def load_department(self):
self.departmentPlusBtn.setParent(None)
jsonDict = {"department": [["temp", "tempPath"], ["temp2", "temp2Path"]]}
for i in range(len(jsonDict["department"])):
layout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(layout)
departmentNameLine = QtWidgets.QLineEdit()
departmentNameLine.setText(jsonDict["department"][i][0])
departmentNameLine.setFixedSize(100,20)
departmentPathLine = QtWidgets.QLineEdit()
departmentPathLine.setText(jsonDict["department"][i][1])
departmentMinusBtn = QtWidgets.QPushButton("-")
departmentMinusBtn.setFixedSize(20,20)
cnt = self.departmentLayout.count()
departmentMinusBtn.clicked.connect(lambda x:self.remove_department(cnt))
layout.addWidget(departmentNameLine)
layout.addWidget(departmentPathLine)
layout.addWidget(departmentMinusBtn)
self.departmentLayout.insertWidget(self.departmentLayout.count(), self.departmentPlusBtn)
def remove_department(self, index):
print index
print self.departmentLayout.children()[0].layout().children()
if __name__ == "__main__":
try:
ui.close
except:
pass
ui = PreferenceUI()
ui.show()
I want
add path line
delete path line
query departmentNameLine, departmentPathLine text
i try ↑, but fail
i try in maya
To keep the logic tidy I have created a class that represents a row, then store the rows in a list to get the texts or to delete the row as I show below:
from functools import partial
from PySide2 import QtWidgets, QtCore, QtGui
class Widget(QtWidgets.QWidget):
def __init__(self, text1, text2, parent=None):
super().__init__(parent)
self.departmentNameLine = QtWidgets.QLineEdit(text1)
self.departmentNameLine.setFixedSize(100, 20)
self.departmentPathLine = QtWidgets.QLineEdit(text2)
self.departmentMinusBtn = QtWidgets.QPushButton("-")
self.departmentMinusBtn.setFixedSize(20, 20)
self.setContentsMargins(0, 0, 0, 0)
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.departmentNameLine)
layout.addWidget(self.departmentPathLine)
layout.addWidget(self.departmentMinusBtn)
class PreferenceUI(QtWidgets.QDialog):
def __init__(self):
super(PreferenceUI, self).__init__()
self.widgets = []
self.setWindowTitle("preference")
self.create_widgets()
self.create_layouts()
self.create_connections()
self.load_department()
def create_widgets(self):
self.departmentPlusBtn = QtWidgets.QPushButton("+")
self.sysAppendWidget = QtWidgets.QTextEdit()
def create_layouts(self):
self.mainLayout = QtWidgets.QFormLayout(self)
self.departmentLayout = QtWidgets.QVBoxLayout()
self.departmentLastLayout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(self.departmentLastLayout)
self.departmentLayout.addWidget(self.departmentPlusBtn)
self.mainLayout.addRow("department :", self.departmentLayout)
self.mainLayout.insertRow(
self.mainLayout.count() - 1, "sys.path.append :", self.sysAppendWidget
)
def create_connections(self):
self.departmentPlusBtn.clicked.connect(self.add_row)
def load_department(self):
jsonDict = {"department": [["temp", "tempPath"], ["temp2", "temp2Path"]]}
for text1, text2 in jsonDict["department"]:
self.create_row(text1, text2)
def save_departament(self):
l = []
for widget in self.widgets:
l.append([self.departmentNameLine.text(), self.departmentPathLine.text()])
jsonDict = {"department": l}
print(jsonDict)
def add_row(self):
self.create_row("text1", "text2")
def create_row(self, text1="", text2=""):
widget = Widget(text1, text2)
widget.departmentMinusBtn.clicked.connect(partial(self.delete, widget))
self.departmentLayout.addWidget(widget)
self.widgets.append(widget)
def delete(self, widget):
if widget in self.widgets:
self.widgets.remove(widget)
widget.deleteLater()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = PreferenceUI()
w.show()
sys.exit(app.exec_())

PyQt accessing Label and LineEdit that are dynamically created

I am trying to access dynamically created Labels and LineEdit to change their texts.
I have no idea how is that possible ?
As an example, when Start button is clicked it should change the text of PS1 QLineEdit from XXXX to YYYY .
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("BiPolar Power Supply Testing")
widget_map = {}
tab_widget = QtWidgets.QTabWidget()
self.setCentralWidget(tab_widget)
pstest_widget = QtWidgets.QWidget()
tab_widget.addTab(pstest_widget, "PS Tests")
pstest_vlay = QtWidgets.QVBoxLayout()
for i in range(1, 9):
title = "PS{}".format(i)
group_box = MainWindow.create_pstest_element(title)
pstest_vlay.addWidget(group_box)
self.PSFStart_btn = QtWidgets.QPushButton("Start")
self.PSFStop_btn = QtWidgets.QPushButton("Stop")
pstest_vlay.addWidget(self.PSFStart_btn)
pstest_vlay.addWidget(self.PSFStop_btn)
pstest_vlay.addStretch()
grid_lay_1 = QtWidgets.QGridLayout(pstest_widget)
#grid_lay_1.addWidget(pstest_widget)
grid_lay_1.addLayout(pstest_vlay, 0, 0)
#staticmethod
def create_pstest_element(title):
group_box = QtWidgets.QGroupBox(title)
grid = QtWidgets.QGridLayout()
serial_label = QtWidgets.QLabel("Serial No:")
serial_lineedit = QtWidgets.QLineEdit("XXXX")
grid.addWidget(serial_label, 0, 0)
grid.addWidget(serial_lineedit, 0, 1)
group_box.setLayout(grid)
return group_box
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Here is how the GUI looks like:
The current design makes it difficult to access the widgets since you do not save access to the elements (you could use a filter using findChildren but that method is not scalable or elegant.).
In these cases it is better than creating a class that inherits from QGroupBox by making internal elements such as the QLabel and QLineEdit class members. On the other hand, having many QGroupBox, it is best to use a container that allows us to access each element by means of an index or key, in this one a list is enough.
class GroupBox(QtWidgets.QGroupBox):
def __init__(self, title, parent=None):
super().__init__(title, parent)
grid = QtWidgets.QGridLayout()
self.serial_label = QtWidgets.QLabel("Serial No:")
self.serial_lineedit = QtWidgets.QLineEdit("XXXX")
grid.addWidget(self.serial_label, 0, 0)
grid.addWidget(self.serial_lineedit, 0, 1)
self.setLayout(grid)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("BiPolar Power Supply Testing")
tab_widget = QtWidgets.QTabWidget()
self.setCentralWidget(tab_widget)
pstest_widget = QtWidgets.QWidget()
tab_widget.addTab(pstest_widget, "PS Tests")
pstest_vlay = QtWidgets.QVBoxLayout()
self.group_boxes = []
for i in range(1, 9):
title = "PS{}".format(i)
group_box = GroupBox(title)
pstest_vlay.addWidget(group_box)
self.group_boxes.append(group_box)
self.PSFStart_btn = QtWidgets.QPushButton("Start")
self.PSFStop_btn = QtWidgets.QPushButton("Stop")
pstest_vlay.addWidget(self.PSFStart_btn)
pstest_vlay.addWidget(self.PSFStop_btn)
pstest_vlay.addStretch()
grid_lay_1 = QtWidgets.QGridLayout(pstest_widget)
# grid_lay_1.addWidget(pstest_widget)
grid_lay_1.addLayout(pstest_vlay, 0, 0)
self.PSFStart_btn.clicked.connect(self.on_start_clicked)
#QtCore.pyqtSlot()
def on_start_clicked(self):
group_box = self.group_boxes[0]
group_box.serial_lineedit.setText("YYYY")

Why QTableWidgetItem doesn't keep updating it's color?

I have a QTableWidget in my program. I want it's rows and columns to change color according to the time entry in the table widget. When I first add the time, it's compared to current system time and the color changing does take effect but as time goes by it doesn't keep up and the colors remain the same. I want it to keep updating table item's color. I cant include all the code as it is too long but I have included the relevant part.
#Operations_Tree is the QTABLEWIDGET
def Scheduler_Loop(self):
Timer = QtCore.QTimer(self)
Timer.start(1000)
Timer.timeout.connect(self.test)
def test(self):
time = QtCore.QTime.currentTime()
current_time_text = time.toString('hh:mm:ss')
for row in range(0,self.Operations_Tree.rowCount()):
time = self.Operations_Tree.item(row,1)
time_text = time.text()
#print(time_text)
if time_text >= current_time_text :
for column in range(0,6):
#print("TEST")
try:
table_widget_item = self.Operations_Tree.item(row, column)
table_widget_item.setForeground(QtGui.QColor(0,0,255)) #BLue
table_widget_item.setBackground(QtGui.QColor(238,233,233)) #
table_widget_item.viewport.update()
except AttributeError:
pass
else:
for column in range(0,6):
#print("TEST")
try:
table_widget_item = self.Operations_Tree.item(row, column)
#table_widget_item.setForeground(QtGui.QColor(0,255,0)) #
table_widget_item.setBackground(QtGui.QColor(238,233,233)) #
table_widget_item.viewport.update()
except AttributeError:
pass
self.Operations_Tree.update()
here is a snap of my program:
For me the main problem is that you are comparing strings instead of time, also in Qt it is not necessary to use try-except since many times they hide errors and waste unnecessary resources, it is better to verify.
PyQt5:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.lcd_number = QtWidgets.QLCDNumber()
self.lcd_number.setFrameShape(QtWidgets.QFrame.NoFrame)
self.lcd_number.setFixedHeight(100)
self.lcd_number.setDigitCount(8)
self.Operations_Tree = QtWidgets.QTableWidget()
self.Operations_Tree.setColumnCount(6)
labels = ["On AIR", "TIME", "ITEM", "DURATION", "B.ITEM", "B.I.DURATION"]
self.Operations_Tree.setHorizontalHeaderLabels(labels)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.lcd_number)
lay.addWidget(self.Operations_Tree)
for i, t in enumerate(("10:10:10", "12:12:12")):
self.Operations_Tree.insertRow(self.Operations_Tree.rowCount())
it = QtWidgets.QTableWidgetItem(t)
self.Operations_Tree.setItem(i, 1, it)
self.resize(640, 480)
self.Scheduler_Loop()
def Scheduler_Loop(self):
Timer = QtCore.QTimer(self)
Timer.timeout.connect(self.test)
Timer.start(1000)
self.test()
#QtCore.pyqtSlot()
def test(self):
time = QtCore.QTime.currentTime()
self.lcd_number.display(time.toString())
for row in range(self.Operations_Tree.rowCount()):
it = self.Operations_Tree.item(row, 1)
r_time = QtCore.QTime.fromString(it.text(), "h:mm:ss")
flag = r_time >= time
f_color = QtGui.QColor(0, 0, 255) if flag else QtGui.QColor(0, 255, 0)
b_color = QtGui.QColor(238, 233, 233) if flag else QtGui.QColor(238,233,233)
for column in range(0, 6):
it = self.Operations_Tree.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.Operations_Tree.setItem(row, column, it)
it.setForeground(f_color)
it.setBackground(b_color)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
PyQt4:
from PyQt4 import QtCore, QtGui
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.lcd_number = QtGui.QLCDNumber()
self.lcd_number.setFrameShape(QtGui.QFrame.NoFrame)
self.lcd_number.setFixedHeight(100)
self.lcd_number.setDigitCount(8)
self.Operations_Tree = QtGui.QTableWidget()
self.Operations_Tree.setColumnCount(6)
labels = ["On AIR", "TIME", "ITEM", "DURATION", "B.ITEM", "B.I.DURATION"]
self.Operations_Tree.setHorizontalHeaderLabels(labels)
lay = QtGui.QVBoxLayout(self)
lay.addWidget(self.lcd_number)
lay.addWidget(self.Operations_Tree)
for i, t in enumerate(("10:10:10", "12:12:12")):
self.Operations_Tree.insertRow(self.Operations_Tree.rowCount())
it = QtGui.QTableWidgetItem(t)
self.Operations_Tree.setItem(i, 1, it)
self.resize(640, 480)
self.Scheduler_Loop()
def Scheduler_Loop(self):
Timer = QtCore.QTimer(self)
Timer.timeout.connect(self.test)
Timer.start(1000)
self.test()
#QtCore.pyqtSlot()
def test(self):
time = QtCore.QTime.currentTime()
self.lcd_number.display(time.toString())
for row in range(self.Operations_Tree.rowCount()):
it = self.Operations_Tree.item(row, 1)
r_time = QtCore.QTime.fromString(it.text(), "h:mm:ss")
flag = r_time >= time
f_color = QtGui.QColor(0, 0, 255) if flag else QtGui.QColor(0, 255, 0)
b_color = QtGui.QColor(238, 233, 233) if flag else QtGui.QColor(238,233,233)
for column in range(0, 6):
it = self.Operations_Tree.item(row, column)
if it is None:
it = QtGui.QTableWidgetItem()
self.Operations_Tree.setItem(row, column, it)
it.setForeground(f_color)
it.setBackground(b_color)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

Add combobox to horizontal header in QTableWidget

I want to create a table in PyQt5 that has a combobox in each column header. When I try to do it, the following error is returned:
TypeError: setHorizontalHeaderItem(self, int, QTableWidgetItem): argument 2 has unexpected type 'QComboBox'
Apparently the function setHorizontalHeaderItem() doesn't accept widgets as items. So is there a way to achieve this? If not, I would settle with putting the comboboxes above the headers, but they should be aligned with the size of each column, even if the user changes the width with the mouse. I don't know if this is possible either.
My code:
from PyQt5 import QtWidgets
import numpy as np
class App(QtWidgets.QWidget):
def __init__(self):
super(App,self).__init__()
self.data = np.random.rand(5,5)
self.createTable()
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.table)
self.setLayout(self.layout)
self.showMaximized()
def createTable(self):
self.header = []
self.table = QtWidgets.QTableWidget(len(self.data), len(self.data[0]))
for i in range(len(self.data[0])):
self.header.append(QtWidgets.QComboBox())
self.header[-1].addItem('Variable')
self.header[-1].addItem('Timestamp')
self.table.setHorizontalHeaderItem(i,self.header[-1])
for i in range(len(self.data)):
for j in range(len(self.data[0])):
self.table.setItem(i,j,QtWidgets.QTableWidgetItem(str(self.data[i][j])))
if __name__ == '__main__':
app = QtWidgets.QApplication([])
ex = App()
app.exec_()
QHeaderView does not support widgets as items so you must create a custom header as I show below:
from PyQt5 import QtCore, QtWidgets
import numpy as np
class HorizontalHeader(QtWidgets.QHeaderView):
def __init__(self, values, parent=None):
super(HorizontalHeader, self).__init__(QtCore.Qt.Horizontal, parent)
self.setSectionsMovable(True)
self.comboboxes = []
self.sectionResized.connect(self.handleSectionResized)
self.sectionMoved.connect(self.handleSectionMoved)
def showEvent(self, event):
for i in range(self.count()):
if i < len(self.comboboxes):
combo = self.comboboxes[i]
combo.clear()
combo.addItems(["Variable", "Timestamp"])
else:
combo = QtWidgets.QComboBox(self)
combo.addItems(["Variable", "Timestamp"])
self.comboboxes.append(combo)
combo.setGeometry(self.sectionViewportPosition(i), 0, self.sectionSize(i)-4, self.height())
combo.show()
if len(self.comboboxes) > self.count():
for i in range(self.count(), len(self.comboboxes)):
self.comboboxes[i].deleteLater()
super(HorizontalHeader, self).showEvent(event)
def handleSectionResized(self, i):
for i in range(self.count()):
j = self.visualIndex(i)
logical = self.logicalIndex(j)
self.comboboxes[i].setGeometry(self.sectionViewportPosition(logical), 0, self.sectionSize(logical)-4, self.height())
def handleSectionMoved(self, i, oldVisualIndex, newVisualIndex):
for i in range(min(oldVisualIndex, newVisualIndex), self.count()):
logical = self.logicalIndex(i)
self.comboboxes[i].setGeometry(self.ectionViewportPosition(logical), 0, self.sectionSize(logical) - 5, height())
def fixComboPositions(self):
for i in range(self.count()):
self.comboboxes[i].setGeometry(self.sectionViewportPosition(i), 0, self.sectionSize(i) - 5, self.height())
class TableWidget(QtWidgets.QTableWidget):
def __init__(self, *args, **kwargs):
super(TableWidget, self).__init__(*args, **kwargs)
header = HorizontalHeader(self)
self.setHorizontalHeader(header)
def scrollContentsBy(self, dx, dy):
super(TableWidget, self).scrollContentsBy(dx, dy)
if dx != 0:
self.horizontalHeader().fixComboPositions()
class App(QtWidgets.QWidget):
def __init__(self):
super(App,self).__init__()
self.data = np.random.rand(10, 10)
self.createTable()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.table)
self.showMaximized()
def createTable(self):
self.header = []
self.table = TableWidget(*self.data.shape)
for i, row_values in enumerate(self.data):
for j, value in enumerate(row_values):
self.table.setItem(i, j, QtWidgets.QTableWidgetItem(str(value)))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

How do I get the contents of a row of QTableWidget with click on the button in python and PyQt

If i click on any of the edit buttons, how do I get the contents of cells in the same row?
class EditButtonsWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(EditButtonsWidget,self).__init__(parent)
btnsave = QtGui.QPushButton('Save')
btnedit = QtGui.QPushButton('edit')
btndelete = QtGui.QPushButton('delete')
layout = QtGui.QHBoxLayout()
layout.setContentsMargins(0,0,0,0)
layout.setSpacing(0)
layout.addWidget(btnsave)
layout.addWidget(btnedit)
layout.addWidget(btndelete)
self.setLayout(layout)
class MainForm(QDialog):
def __init__(self,parent=None):
super(MainForm,self).__init__(parent)
self.resize(400,200)
self.tableWidget = QTableWidget()
layout = QVBoxLayout()
layout.addWidget( self.tableWidget)
self.setLayout(layout)
self.init_main_form()
def bb(self):
button = QtGui.QApplication.focusWidget()
index = self.tableWidget.indexAt(button.pos())
if index.isValid():
print(index.row(), index.column())
def init_main_form(self):
data =[['a','b','c','d'],['z','y','x','w']]
self.tableWidget.setColumnCount(5)
for row in data:
inx = data.index(row)
self.tableWidget.insertRow(inx)
self.tableWidget.setItem(inx,0,QTableWidgetItem(str(row[0])))
self.tableWidget.setItem(inx,1,QTableWidgetItem(str(row[1])))
self.tableWidget.setItem(inx,2,QTableWidgetItem(str(row[2])))
self.tableWidget.setItem(inx,3,QTableWidgetItem(str(row[3])))
self.tableWidget.setCellWidget(inx,4,EditButtonsWidget())
def main():
app = QApplication(sys.argv)
main_form = MainForm()
main_form.show()
app.exec_()
if __name__ == '__main__':
main()
Implemented signals and slots and now you will get idea how you can handle it
And mixing imports is not really a good idea
from PyQt4 import QtCore, QtGui
import sys
class EditButtonsWidget(QtGui.QWidget):
editCalled = QtCore.pyqtSignal(str)
def __init__(self, row, col, parent=None,):
super(EditButtonsWidget,self).__init__(parent)
self.row = row
self.col = col
self.parent = parent
btnsave = QtGui.QPushButton('Save')
btnedit = QtGui.QPushButton('edit')
btndelete = QtGui.QPushButton('delete')
layout = QtGui.QHBoxLayout()
layout.setContentsMargins(0,0,0,0)
layout.setSpacing(0)
layout.addWidget(btnsave)
layout.addWidget(btnedit)
layout.addWidget(btndelete)
self.setLayout(layout)
btnedit.clicked.connect(self.getAllCellVal)
#QtCore.pyqtSlot()
def getAllCellVal(self):
itmVal = {}
for col in range(0, 4):
itm = self.parent.item(self.row, col).text()
itmVal[col] = str(itm)
if itmVal:
self.editCalled.emit(str(itmVal))
class MainForm(QtGui.QDialog):
def __init__(self,parent=None):
super(MainForm,self).__init__(parent)
self.resize(400,200)
self.tableWidget = QtGui.QTableWidget()
layout = QtGui.QVBoxLayout()
layout.addWidget( self.tableWidget)
self.setLayout(layout)
self.init_main_form()
def bb(self):
button = QtGui.QApplication.focusWidget()
index = self.tableWidget.indexAt(button.pos())
if index.isValid():
print(index.row(), index.column())
def printEditVal(self, values):
print values
def init_main_form(self):
data =[['a','b','c','d'],['z','y','x','w']]
self.tableWidget.setColumnCount(5)
for row in data:
inx = data.index(row)
self.tableWidget.insertRow(inx)
self.tableWidget.setItem(inx,0,QtGui.QTableWidgetItem(str(row[0])))
self.tableWidget.setItem(inx,1,QtGui.QTableWidgetItem(str(row[1])))
self.tableWidget.setItem(inx,2,QtGui.QTableWidgetItem(str(row[2])))
self.tableWidget.setItem(inx,3,QtGui.QTableWidgetItem(str(row[3])))
buttonWid = EditButtonsWidget(inx,4, self.tableWidget)
buttonWid.editCalled.connect(self.printEditVal)
self.tableWidget.setCellWidget(inx,4,buttonWid)
def main():
app = QtGui.QApplication(sys.argv)
main_form = MainForm()
main_form.show()
app.exec_()
if __name__ == '__main__':
main()

Categories

Resources