PyQt accessing Label and LineEdit that are dynamically created - python

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")

Related

How change radio button of Radio Button Group in cell of Table programatically?

I want to change the selected radio button in group of radio button in cell table programatically.
I try to recreate table after change the status in piece object but if I have many records it becomes slow.
I have the next code:
import sys
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QHBoxLayout, QWidget, QButtonGroup, \
QRadioButton, QVBoxLayout, QPushButton, QApplication
class Piece:
def __init__(self, init, name, status):
self.init = init
self.name = name
self.status = status
class Table(QWidget):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
self.debug_data()
self.fila = 0
self.init_ui()
def debug_data(self):
print("okay")
self.pieces: [Piece] = []
self.pieces.append(Piece('2021-01-11 13:52:00', 'Router 234', 1))
self.pieces.append(Piece('2021-01-11 13:55:00', 'Router AB', 0))
self.pieces.append(Piece('2021-01-11 14:00:00', 'Router A234E', 1))
self.pieces.append(Piece('2021-01-11 14:01:00', 'Router Sufle', 0,))
def _create_buttons(self):
self.buttons_layout = QHBoxLayout()
self.btn_ok_all = QPushButton("All Manual")
self.btn_no_ok_all = QPushButton("All Automatic")
self.btn_no_validate_all = QPushButton("All Hybrid")
self.buttons_layout.addWidget(self.btn_ok_all)
self.buttons_layout.addWidget(self.btn_no_ok_all)
self.buttons_layout.addWidget(self.btn_no_validate_all)
self.layout.addLayout(self.buttons_layout)
def init_ui(self):
self.createTable()
self.layout = QVBoxLayout()
self._create_buttons()
self.layout.addWidget(self.tableWidget)
self.setLayout(self.layout)
self.show()
def createTable(self):
self.tableWidget = QTableWidget()
self.tableWidget.setColumnCount(3)
self.tableWidget.setHorizontalHeaderLabels(
["Init Time", "Name", "Type"])
self.process_rows()
def process_rows(self):
for piece in self.pieces:
self.add_row(piece)
def add_row(self, piece):
self.tableWidget.insertRow(self.fila)
self.tableWidget.setItem(self.fila, 0, QTableWidgetItem(piece.init))
self.tableWidget.setItem(self.fila, 1, QTableWidgetItem(piece.name))
self.tableWidget.setCellWidget(self.fila, 2, self.create_group_radio_button(piece))
self.fila = self.fila + 1
def create_group_radio_button(self, piece):
layout = QHBoxLayout()
widget = QWidget(self)
widget.setLayout(layout)
number_group = QButtonGroup(widget)
manual = QRadioButton("Manual")
number_group.addButton(manual)
automatic = QRadioButton("Automatic")
number_group.addButton(automatic)
hybrid = QRadioButton("Hybrid")
number_group.addButton(hybrid)
layout.addWidget(manual)
layout.addWidget(automatic)
layout.addWidget(hybrid)
if piece.status == 0:
hybrid.setChecked(True)
elif piece.status == 1:
manual.setChecked(True)
else:
automatic.setChecked(True)
return widget
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Table()
sys.exit(app.exec_())
What is the way to change one of them programatically?
How to access the cell widget and select the button to change it?
This is a situation for which creating a class is probably the best approach: it improves the object structure and allows creation of functions that give easier access to it.
class PieceSelector(QWidget):
def __init__(self, piece):
super().__init__()
self.piece = piece
layout = QHBoxLayout(self)
self.number_group = QButtonGroup(self)
manual = QRadioButton("Manual", 1)
self.number_group.addButton(manual)
automatic = QRadioButton("Automatic", 2)
self.number_group.addButton(automatic)
hybrid = QRadioButton("Hybrid", 0)
self.number_group.addButton(hybrid)
layout.addWidget(manual)
layout.addWidget(automatic)
layout.addWidget(hybrid)
self.number_group.button(piece.status).setChecked(True)
def get_status(self):
return self.number_group.checkedId()
def set_status(self, status):
self.number_group.button(status).setChecked(True)
Then you just add the widget by creating the instance and get it back using cellWidget():
def add_row(self, piece):
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
self.tableWidget.setItem(row, 0, QTableWidgetItem(piece.init))
self.tableWidget.setItem(row, 1, QTableWidgetItem(piece.name))
self.tableWidget.setCellWidget(row, 2, PieceSelector(piece))
def set_status_for_row(self, row, status):
self.tableWidget.cellWidget(row, 2).set_status(status)

button overlapping checkbox text

I try to code in PyQt an interface where user can check boxes and then click on the button to process their choices. However, I have some trouble because the button overlaps checkbox labels. Here is a simpler code to show you my problem :
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QTabWidget, QVBoxLayout, QGridLayout, \
QCheckBox, QHBoxLayout
import sys
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 tabs - pythonspot.com'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.show()
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.tab2 = QWidget()
self.tabs.resize(300, 200)
self.checkbox_states = {}
# Add tabs
self.tabs.addTab(self.tab2, "Tab 2")
# Create first tab
self.tab2.layout = QGridLayout()
checkbox_layout = QVBoxLayout()
self.checkbox_states["Haar"] = QCheckBox("small")
self.checkbox_states["db"] = QCheckBox("small")
self.checkbox_states["sym"] = QCheckBox("small")
self.checkbox_states["coif"] = QCheckBox("very very very very long")
for key, l in self.checkbox_states.items():
l.setChecked(False)
checkbox_layout.addWidget(l)
process_button_layout = QHBoxLayout()
self.process_wavelet = QPushButton("Process")
process_button_layout.addWidget(self.process_wavelet)
# QObject.connect(self.process_wavelet, SIGNAL('clicked()'), self._on_process_wavelet)
self.tab2.layout.addLayout(checkbox_layout, 0, 0, 0, 0)
self.tab2.layout.addLayout(process_button_layout, 1, 1, 1, 1)
self.tab2.setLayout(self.tab2.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Does anyone has an idea on how i can suppress this overlapping problem ? Thanks !
EDIT :
I would like something like this :
Here with a much smaller text, I don't have the overlapping problem. It only appear if we replace the last checkbox's label by a longer string.
What the OP wants can be obtained from many depending on how he wants the geometries of the elements to behave when the window changes in size. So as there are no more restrictions than the image it shows, it will provide a possible solution using QGridLayout where in the first column the QCheckBox will be placed, and in the second column and in the last file the QPushButton:
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
layout = QVBoxLayout(self)
self.tabs = QTabWidget()
self.tabs.resize(300, 200)
layout.addWidget(self.tabs)
self.tab2 = QWidget()
self.tabs.addTab(self.tab2, "Tab 2")
lay = QGridLayout(self.tab2)
self.checkbox_states = {}
for i, (key, text) in enumerate(
(
("Haar", "small"),
("db", "small"),
("sym", "small"),
("coif", "very very very very long"),
)
):
checkbox = QCheckBox(text)
checkbox.setChecked(False)
lay.addWidget(checkbox, i, 0)
self.checkbox_states[key] = checkbox
self.process_wavelet = QPushButton("Process")
lay.addWidget(self.process_wavelet, i, 1)

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_())

Programming a GUI with PyQt in Python3

I'm asked to create a GUI with PyQt without using any Qtdesigner for my assignment. But now I'm facing a problem. In this pic GUI screenshoot
as you can see, there is a spinbox "Anzahl der Schicht". What I want to do is, when the user sets the value for this spinbox, the area which below it will show the corresponding rows of the input(the combination of QLineEdit,QSlider Widget,QLineEdit and 2 QSpinboxes in a row).
For example, the pic that I uploaded, means the value of spinbox "Anzahl der Schicht" is 3, so there are 3 rows below it. If the value is 4, there should be 4 rows. There is no limited value for the spinbox. How can I make this kind of dynamic effect for the GUI?
Update on 05.07.2019
Thanks for all useful replies. The following code and pic GUI version2 is my current status. So far I can't connect the Qspinbox to the class Widget() for adding or deleting the rows. So I just use a button "add widget" to implement what I want.
class ExampleWidget(QtWidgets.QGroupBox):
def __init__(self, numAddWidget):
QtWidgets.QGroupBox.__init__(self)
self.numAddWidget = numAddWidget
self.initSubject()
self.organize()
self.setFlat(True)
self.setStyleSheet("border: 1px solid transparent")
def initSubject(self):
self.shiftname =QtWidgets.QLineEdit() # Eingabefeld init
self.shiftname.setText('0')
self.shiftpercent = QtWidgets.QSlider()
self.shiftpercent.setOrientation(QtCore.Qt.Horizontal)
self.carnum =QtWidgets.QLineEdit() # Eingabefeld init
self.carnum.setText('0')
self.start = QtWidgets.QTimeEdit()
self.start.setDisplayFormat("HH:mm")
self.end = QtWidgets.QTimeEdit()
self.end.setDisplayFormat("HH:mm")
def organize(self):
grid = QtWidgets.QGridLayout(self)
self.setLayout(grid)
grid.addWidget(self.shiftname, 0,0)
grid.addWidget(self.shiftpercent, 0,1)
grid.addWidget(self.carnum, 0,2)
grid.addWidget(self.start, 0,3)
grid.addWidget(self.end, 0,4)
class Widget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.numAddWidget = 1
self.initUi()
def initUi(self):
self.layoutV = QtWidgets.QVBoxLayout(self)
self.area = QtWidgets.QScrollArea(self)
self.area.setWidgetResizable(True)
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.layoutH = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
self.gridLayout = QtWidgets.QGridLayout()
self.layoutH.addLayout(self.gridLayout)
self.area.setWidget(self.scrollAreaWidgetContents)
self.add_button = QtWidgets.QPushButton("Add Widget")
self.layoutV.addWidget(self.add_button)
self.layoutV.addWidget(self.area)
self.add_button.clicked.connect(self.addWidget)
self.widget = ExampleWidget(self.numAddWidget)
self.gridLayout.addWidget(self.widget)
def addWidget(self):
self.numAddWidget += 1
self.widget = ExampleWidget(self.numAddWidget)
self.gridLayout.addWidget(self.widget)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Here is a way. In this example the widgets (QLineEdits in this case) are stored in a list, Widget.items. When the value of the spin box changes extra widgets are appended to this list and added to the vertical layout if necessary. The widgets are then shown or hidden depending whether the current number of visible widgets is greater or smaller than the value of the spin box.
from PyQt5 import QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super().__init__()
self.resize(500,500)
self.items = []
self.item_count = 0
self.item_factory = QtWidgets.QLineEdit
group_box = QtWidgets.QGroupBox()
self.item_layout = QtWidgets.QVBoxLayout(group_box)
self.item_layout.addStretch(2)
self.spin_box = QtWidgets.QSpinBox(self)
self.spin_box.valueChanged.connect(self.set_item_count)
h_layout = QtWidgets.QHBoxLayout(self)
h_layout.addWidget(group_box, 2)
h_layout.addWidget(self.spin_box, 0)
def set_item_count(self, new_count:int):
n_items = len(self.items)
for ii in range(n_items, new_count):
item = self.item_factory(self)
self.items.append(item)
self.item_layout.insertWidget(n_items, item)
for ii in range(self.item_count, new_count):
self.item_layout.itemAt(ii).widget().show()
for ii in range(new_count, self.item_count):
self.item_layout.itemAt(ii).widget().hide()
self.item_count = new_count
if __name__ == "__main__":
app = QtWidgets.QApplication([])
window = Widget()
window.show()
app.exec()

How to add dropdown menu to QMessageBox?

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()

Categories

Resources