List of open QtiPlot windows - python

I'm writing a plugin for QtiPlot using Python. Within the GUI of this plugin I'd like to display a dropdown that holds a list of all open windows of one sort of window (plots, tables, notes, etc.). On click on, for example, a item of a dropdown holding tables, I'd like to load this table to work with it. Are there any suggestions how to solve this problem?
The only thing I found is paragraph 7.2.6 of the QtiPlot-Manual.
EDIT:
I'm now a step ahead. I'm now able to fetch a list of the subwindow names. But now I have a problem displaying the gui within the gtiplot scripting-window using the following code.
# Import system libraries.
import os,sys
# Import Qt modules.
from PyQt4 import QtCore,QtGui
class Widget(QtGui.QMainWindow):
def __init__(self):
super(Widget, self).__init__();
self.initUI();
def initUI(self):
# Set the window label.
self.lbl = QtGui.QLabel("", self);
# Fetch the QMdiArea object ...
ws = workspace();
# ... and fetch all subwindows.
subs = ws.subWindowList();
# Initialize the combobox ...
combo = QtGui.QComboBox(self);
# ... and add the items.
for sub in subs:
combo.addItem(sub.objectName());
combo.move(50, 50);
self.lbl.move(50, 150);
combo.activated[str].connect(self.onActivated);
self.setGeometry(300, 300, 300, 200);
self.setWindowTitle('Subwindow DropDown');
self.show();
def onActivated(self, text):
self.lbl.setText(text);
self.lbl.adjustSize();
def main():
app = QtGui.QApplication(sys.argv);
widget = Widget();
sys.exit(app.exec_());
if __name__ == '__main__':
main();

import os,sys
from PyQt4 import QtCore,QtGui
class Widget(QtGui.QMainWindow):
def __init__(self):
super(Widget, self).__init__();
self.initUI();
def initUI(self):
# Set the window label.
self.lbl = QtGui.QLabel("", self);
# Fetch the QMdiArea object ...
ws = workspace();
# ... and fetch all subwindows.
subs = ws.subWindowList();
# Initialize the combobox ...
combo = QtGui.QComboBox(self);
# ... and add the items.
for sub in subs:
combo.addItem(sub.objectName());
combo.move(50, 50);
self.lbl.move(50, 150);
combo.activated[str].connect(self.onActivated);
self.setGeometry(300, 300, 300, 200);
self.setWindowTitle('Subwindow DropDown');
self.show();
def onActivated(self, text):
self.lbl.setText(text);
self.lbl.adjustSize();
widget = Widget();
I hope this helps!

Related

PyQt5 dynamic creation/destruction of widgets

I have an application where upon start up the user is presented with a dialog to chose number of 'objects' required. This then generates necessary objects in the main window using a for loop (i.e. object1, object2, etc.). I want to move this selection into the main window so that this can be changed without the need to restart the application. I have no idea how to approach this as I'm not sure how to dynamically create/destroy once the application is running. Here's an example code that generates tabs in a tab widget with some elements in each tab.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class SelectionWindow(QDialog):
def __init__(self):
QDialog.__init__(self)
self.settings = QSettings('Example', 'Example')
self.numberOfTabs = QSpinBox(value = self.settings.value('numberOfTabs', type=int, defaultValue = 3), minimum = 1)
self.layout = QFormLayout(self)
self.button = QPushButton(text = 'OK', clicked = self.buttonClicked)
self.layout.addRow('Select number of tabs', self.numberOfTabs)
self.layout.addRow(self.button)
def buttonClicked(self):
self.settings.setValue('numberOfTabs', self.numberOfTabs.value())
self.accept()
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.settings = QSettings('Example', 'Example')
self.tabs = self.settings.value('numberOfTabs', type = int)
self.tabWidget = QTabWidget()
for i in range(1, self.tabs + 1):
exec(('self.tab{0} = QWidget()').format(i))
exec(("self.tabWidget.addTab(self.tab{0}, 'Tab{0}')").format(i))
exec(('self.lineEdit{0} = QLineEdit()').format(i))
exec(('self.spinBox{0} = QSpinBox()').format(i))
exec(('self.checkBox{0} = QCheckBox()').format(i))
exec(('self.layout{0} = QFormLayout(self.tab{0})').format(i))
exec(("self.layout{0}.addRow('Name', self.lineEdit{0})").format(i))
exec(("self.layout{0}.addRow('Value', self.spinBox{0})").format(i))
exec(("self.layout{0}.addRow('On/Off', self.checkBox{0})").format(i))
self.setCentralWidget(self.tabWidget)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
dialog = SelectionWindow()
dialog.show()
if dialog.exec_() == SelectionWindow.Accepted:
mainwindow = MainWindow()
mainwindow.show()
sys.exit(app.exec_())
First of all, you should never use exec for things like these. Besides the security issues of using exec, it also makes your code less readable (and then much harder to debug) and hard to interact with.
A better (and more "elegant") solution is to use a common function to create tabs and, most importantly, setattr.
Also, you shouldn't use QSettings in this way, as it is mostly intended for cross-session persistent data, not to initialize an interface. For that case, you should just override the exec() method of the dialog and initialize the main window with that value as an argument.
And, even if it was the case (but I suggest you to avoid the above approach anyway), remember that to make settings persistent, at least organizationName and applicationName must be set.
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.settings = QSettings('Example', 'Example')
# this value does not need to be a persistent instance attribute
tabCount = self.settings.value('numberOfTabs', type = int)
# create a main widget for the whole interface
central = QWidget()
mainLayout = QVBoxLayout(central)
tabCountSpin = QSpinBox(minimum=1)
mainLayout.addWidget(tabCountSpin)
tabCountSpin.setValue(tabCount)
tabCountSpin.valueChanged.connect(self.tabCountChanged)
self.tabWidget = QTabWidget()
mainLayout.addWidget(self.tabWidget)
for t in range(tabCount):
self.createTab(t)
self.setCentralWidget(central)
def createTab(self, t):
t += 1
tab = QWidget()
self.tabWidget.addTab(tab, 'Tab{}'.format(t))
layout = QFormLayout(tab)
# create all the widgets
lineEdit = QLineEdit()
spinBox = QSpinBox()
checkBox = QCheckBox()
# add them to the layout
layout.addRow('Name', lineEdit)
layout.addRow('Value', spinBox)
layout.addRow('On/Off', checkBox)
# keeping a "text" reference to the widget is useful, but not for
# everything, as tab can be accessed like this:
# tab = self.tabWidget.widget(index)
# and so its layout:
# tab.layout()
setattr(tab, 'lineEdit{}'.format(t), lineEdit)
setattr(tab, 'spinBox{}'.format(t), spinBox)
setattr(tab, 'checkBox{}'.format(t), checkBox)
def tabCountChanged(self, count):
if count == self.tabWidget.count():
return
elif count < self.tabWidget.count():
while self.tabWidget.count() > count:
# note that I'm not deleting the python reference to each object;
# you should use "del" for both the tab and its children
self.tabWidget.removeTab(count)
else:
for t in range(self.tabWidget.count(), count):
self.createTab(t)

Accessing to QListWidgetItem from widget inside

I'm trying to figure out how I can get the QWidget that I insert into a QListWidget as a QListWidgetItem to be able to access the list it is a part of so that it can do the following:
Increase/decrease it's position in the list
Remove itself from the list
Pass information from it's own class to a function in the main class
My script layout is a main.py which is where the MainWindow class is. The MainWindow uses the class generated from the main ui file. I also have the custom widget which is it's own class.
Example of GUI:
Relevant code snippets:
main.py
from PyQt4.QtGui import QMainWindow, QApplication
from dungeonjournal import Ui_MainWindow
from creature_initiative_object import InitCreatureObject
from os import walk
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(QMainWindow, self).__init__(parent)
self.setupUi(self)
etc......
def AddToInitiative(self):
creature = self.comboBoxSelectCharacter.currentText()
if(creature):
creatureInfo = ''
with open("creatures/"+str(creature)+".creature", "r") as f:
creatureInfo = f.read()
creatureInfo = creatureInfo.split("|")
customWidget = InitCreatureObject()
customWidgetItem = QtGui.QListWidgetItem(self.initiativeList)
customWidgetItem.setSizeHint(QtCore.QSize(400,50))
self.initiativeList.addItem(customWidgetItem)
self.initiativeList.setItemWidget(customWidgetItem, customWidget)
customWidget.setName(creatureInfo[0])
return
creature_initiative_object.py
class Ui_InitCreatureObject(object):
def setupUi(self, InitCreatureObject):
etc...
class InitCreatureObject(QtGui.QWidget, Ui_InitCreatureObject):
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.setupUi(self)
Edit 1:
To clarify again, I need to be able to use the buttons in the widget to modify the position of itself in the list. The list is part of the main ui. The buttons for up arrow, down arrow, Select, and Remove are the one's I'm trying to get to interact with things outside of their class.
The function they call needs to be able to determine which listItem is being called, be able to modify the list.
For example, if I click remove, it then needs to know which item in the list to remove. So it needs to first know what the list is, then it needs to know what item it is. I'm not sure how to access the instance of the widget that is occupying that listitem. I also am not sure how to get that listitem based on a button press from inside that listitem's class.
Edit 2:
Per the first answer I tried to work that into my code.
main.py had the following function added
def RemoveItem(self):
cwidget = self.sender().parent()
item = self.initiativeList.itemAt(cwidget.pos())
row = self.initiativeList.row(item)
self.initiativeList.takeItem(row)
print(row)
creature_initiative_object.py had the following added to the InitCreatureObject class
class InitCreatureObject(QtGui.QWidget, Ui_InitCreatureObject):
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.setupUi(self)
self.mainwidget = main.MainWindow()
self.btnRemove.clicked.connect(self.mainwidget.RemoveItem)
Item is still not being passed. The parent object seems to be right but when I get the row it always says -1.
The strategy to get the QTableWidgetItem is to use the itemAt() method but for this you must know the position of some point within the QTableWidgetItem.
Since the main objective is to get the item when a signal is sent, then the connected slot is used, so I recommend connecting all the signals to that slot. Given the above the following steps are taken:
Get the object that emits the signal through sender().
Get the sender parent() since this will be the custom widget that was added to the QListWidget() along with the item.
Get the position of the custom widget through pos(), this is the position that should be used in the itemAt() method.
Then you get the text of the button or some parameter that tells me the task to know what action you want to do.
The above can be implemented as follows:
def someSlot(self):
p = self.sender().parent()
it = self.lw.itemAt(p.pos())
text = self.sender().text()
if text == "task1":
do task1
elif text == "task2":
do task2
From the above, the following example is proposed:
class CustomWidget(QWidget):
def __init__(self, text, parent=None):
QWidget.__init__(self, parent)
self.setLayout(QHBoxLayout())
self.buttons = []
vb = QVBoxLayout()
self.layout().addLayout(vb)
self.btnTask1 = QPushButton("task1")
self.btnTask2 = QPushButton("task2")
vb.addWidget(self.btnTask1)
vb.addWidget(self.btnTask2)
self.buttons.append(self.btnTask1)
self.buttons.append(self.btnTask2)
self.btnTask3 = QPushButton("task3")
self.btnTask4 = QPushButton("task4")
self.btnTask5 = QPushButton("task5")
self.btnTask6 = QPushButton("task6")
self.layout().addWidget(self.btnTask3)
self.layout().addWidget(self.btnTask4)
self.layout().addWidget(self.btnTask5)
self.layout().addWidget(self.btnTask6)
self.buttons.append(self.btnTask3)
self.buttons.append(self.btnTask4)
self.buttons.append(self.btnTask5)
self.buttons.append(self.btnTask6)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.lw = QListWidget(self)
self.setCentralWidget(self.lw)
for i in range(5):
cw = CustomWidget("{}".format(i))
for btn in cw.buttons:
btn.clicked.connect(self.onClicked)
item = QListWidgetItem(self.lw)
item.setSizeHint(QSize(400, 80))
self.lw.addItem(item)
self.lw.setItemWidget(item, cw)
def onClicked(self):
p = self.sender().parent()
it = self.lw.itemAt(p.pos())
row = self.lw.row(it)
text = self.sender().text()
print("item {}, row {}, btn: {}".format(it, row, text))
#if text == "task1":
# do task1
#elif text == "task2":
# do task2
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
In your Case:
class MainWindow(QMainWindow, Ui_MainWindow):
[...]
def AddToInitiative(self):
[...]
customWidget = InitCreatureObject()
customWidget.btnRemove.clicked.connect(self.RemoveItem)
# ^^^^^
[...]
def RemoveItem(self):
cwidget = self.sender().parent()
item = self.initiativeList.itemAt(cwidget.pos())
row = self.initiativeList.row(item)
self.initiativeList.takeItem(row)
print(row)

How do I put a QComboBox inside QColumnView

Scenario: I need to put a combo box inside the 4th column in qcolumnview, so the user can choose ON or OFF.
Description: In the future this will be saved as an XML file, so the user can select the parameter and generate a custom XML file.
Can someone tell me how do I do that?
import sys
from PyQt4 import QtGui, QtCore
class xml_creator(QtGui.QMainWindow):
def __init__(self):
super(xml_creator, self).__init__()
self.initUI()
def initUI(self):
column_view = QtGui.QColumnView(self)
self.setCentralWidget(column_view)
m_model = QtGui.QStandardItemModel()
column_view.setModel(m_model)
column_view.setAlternatingRowColors(True)
self.test_variables = {}
self.test_variables['OPTION_1'] = ['OFF', 'ON']
self.test_variables['OPTION_2'] = ['OFF', 'ON']
self.iq_xml = {}
self.iq_xml['TEST_1'] = {}
self.iq_xml['TEST_1']['Test_case_1'] = self.test_variables
for x in self.iq_xml:
if not self.iq_xml[x]:
continue
parent = QtGui.QStandardItem(x)
parent.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
for y in self.iq_xml[x]:
if not self.iq_xml[x][y]:
continue
child0 = QtGui.QStandardItem(y)
child0.setFlags(QtCore.Qt.ItemIsEnabled)
parent.appendRow(child0)
for z in self.iq_xml[x][y]:
if not self.iq_xml[x][y][z]:
continue
grand_child = QtGui.QStandardItem(z)
grand_child.setFlags(QtCore.Qt.ItemIsEnabled)
child0.appendRow(grand_child)
value = self.iq_xml[x][y][z]
grand_grand_child = QtGui.QStandardItem(str(value))
grand_grand_child.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
grand_child.appendRow(grand_grand_child)
column_view.model().appendRow(parent)
column_view.setColumnWidths([200, 200, 200, 100])
self.setGeometry(300, 300, 1000, 300)
self.setWindowTitle('IQ XML Creator')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = xml_creator()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I could not find a solution for that but I found a workaround, so I'm posting hoping to help who has the same problem as me.
Once I couldnt put the combobox in the QColumnView as I was trying, my workaround was to create a table filled with the comboboxes I wanted, and then setting this QTable as the preview widget in QColumnView.

Setting multiple initial values in PyQt form

I have been trying to create a settings window for an application I'm developing and I want to populate the settings window with either a config file (which I will later write the answers to) or the system defaults if the config file is absent or cannot be opened.
I have seen examples where a few values are populated after the setupUi(self) is executed, however I have around 15-20 values and so having 2 huge if statements seems messy. Here is my current state of affairs and I can't figure out how to make it call the function I have created getConfig
Is this the best way to populate values? Or is there something else I should try?
class SettingsWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_SettingsWindow()
self.ui.setupUi(self)
self.ui.getConfig(self) #my problem is here
... #all the action bindings
def getConfig(self):
if not os.path.exists('app.config'):
self.ui.setDefaults(self) #fallback to defaults if no config file
with open('app.config') as f:
self.config = json.load(f)
... #bind all the default values
Here is an example using a dictionary to store the widgets - see my comment.
Only one EditLine updated but principal is there (Note the label could also be updated in the same way.
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget): # any super class is okay
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.settings = {}
var_label = QtGui.QLabel('Path')
self.settings['path'] = QtGui.QLineEdit(width=200)
quitbutton = QtGui.QPushButton('Quit')
loadbutton = QtGui.QPushButton('Load Settings')
savebutton = QtGui.QPushButton('Save Settings')
layout1 = QtGui.QHBoxLayout()
layout1.addWidget(var_label)
layout1.addWidget(self.settings['path'])
layout2 = QtGui.QHBoxLayout()
layout2.addWidget(loadbutton)
layout2.addWidget(savebutton)
layout2.addWidget(quitbutton)
layout = QtGui.QVBoxLayout()
layout.addLayout(layout1)
layout.addLayout(layout2)
self.setLayout(layout)
loadbutton.clicked.connect(self.get_config)
savebutton.clicked.connect(self.save_settings)
quitbutton.clicked.connect(QtGui.qApp.quit)
self.get_config()
def get_config(self):
# Read config file here into dictionary
# Example
config_data = {'path':'data path here'} # Example dictionary created when reading config file
for key in config_data:
self.settings[key].setText(config_data[key])
def save_settings(self): # Link to button
data = {}
for key in self.settings:
data[key] = self.settings[key].text()
# Save to config file here
print (data)
if __name__ == '__main__':
app = QtGui.QApplication([])
window = MyWindow()
window.show()
app.exec_()
If the widgets you use are not set by setText() or retrieved by text() then the code is a little more complex, various ways of doing that for TextEdit, Lists, Combo etc. can be incorporated.

Populating the UI from a text file - python

I broke my question down to a very basic setup. Each tab allows a user to click a button and append and item to the list. At the same time the item is added to the list, it's also added to a global variable called ALLITEMs. Each tab is given it's over dictionary to append to as seen here..
ALLITEMS = {
"A" : [],
"B" : []
}
In the main widget on the 'closeEvent' i save this variable to a json file. Also in the main widgets 'showEvent' i load this data back into the global bariable ALLITEMS. This allows users to retain the data each time the launch the application. What I'm not sure about is how to refresh the tab widgets to repopulate the GUI's with the data from the variable. But only when the tool is initially launched. I don't want it to load each time the user clicks that tab, that would produce duplicate data.
import sys
import json
import os
from PySide import QtGui, QtCore
ALLITEMS = {
"A" : [],
"B" : []
}
# Widgets
# ------------------------------------------------------------------------------
class ExampleA(QtGui.QWidget):
def __init__(self):
super(ExampleA, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(550, 400)
self.setWindowTitle("Tab A")
# widgets
self.ui_listview = QtGui.QListWidget()
self.ui_add = QtGui.QPushButton("Add Item")
# signals
self.ui_add.clicked.connect(self.add_item_clicked)
# main layout
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(self.ui_add)
main_layout.addWidget(self.ui_listview)
main_layout.setContentsMargins(0,0,0,0)
self.setLayout(main_layout)
def add_item_clicked(self):
global ALLITEMS
item = "Another item A"
ALLITEMS["A"].append(item)
self.ui_listview.addItem( item )
class ExampleB(QtGui.QWidget):
def __init__(self):
super(ExampleB, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(550, 400)
self.setWindowTitle("Tab A")
# widgets
self.ui_listview = QtGui.QListWidget()
self.ui_add = QtGui.QPushButton("Add Item")
# signals
self.ui_add.clicked.connect(self.add_item_clicked)
# main layout
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(self.ui_add)
main_layout.addWidget(self.ui_listview)
main_layout.setContentsMargins(0,0,0,0)
self.setLayout(main_layout)
def add_item_clicked(self):
global ALLITEMS
item = "Another item B"
ALLITEMS["B"].append(item)
self.ui_listview.addItem( item )
class ExampleMain(QtGui.QWidget):
def __init__(self):
super(ExampleMain, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(200, 200)
self.setWindowTitle("Test")
# widgets
tab_panel = QtGui.QTabWidget()
tab_panel.addTab(ExampleA(), "Tab A")
tab_panel.addTab(ExampleB(), "Tab B")
# main layout
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(tab_panel)
main_layout.setContentsMargins(0,0,0,0)
self.setLayout(main_layout)
def closeEvent(self, event):
self.save_data()
def showEvent(self, event):
self.load_data()
def save_data(self):
print "Saving..."
global ALLITEMS
json.dump(ALLITEMS, open("Example_Data.json",'w'), indent=4)
def load_data(self):
global ALLITEMS
if os.path.exists( "Example_Data.json" ):
with open( "Example_Data.json" ) as f:
data = json.load(f)
ALLITEMS = data
# Main
# ------------------------------------------------------------------------------
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = ExampleMain()
ex.show()
sys.exit(app.exec_())
The simpliest (although not very effective) way would be to update list widget from ALLITEMS dictionary each time you change it. So on every button press you could update ALLITEMS first, then clear the content of list widget and refill it according to new value of ALLITEMS["TabName"]. Then on show event you could do the same - load ALLITEMS from file once and then update list widget.
For more effective approach take a look at Qt Model/View programming (http://doc.qt.io/qt-5/model-view-programming.html) You will probably need to replace QListWidget with QListView
I would remove the global variable entirely.
In your closeEvent, instead of saving the global variable, read the items from the listview directly and save them. In your add_item method, don't modify the global variable at all.
Then in your load_data function, read the data from the file and add the items to the listviews.
You will need to store references to the ex.ample widgets
self.example_a = ExampleA()
self.example_b = ExampleB()
tab_panel.addTab(self.example_a), "Tab A")
tab_panel.addTab(self.example_b), "Tab B")
Here's how you could save and load the data:
def save_data(self):
print "Saving..."
all_items = {}
for i in range(self.example_a.ui_listview.count()):
text = self.example_a.ui_listview.item(i).text()
all_items.set_default('A', []).append(text)
for i in range(self.example_b.ui_listview.count()):
text = self.example_b.ui_listview.item(i).text()
all_items.set_default('B', []).append(text)
json.dump(all_items, open("Example_Data.json",'w'), indent=4)
def load_data(self):
if os.path.exists( "Example_Data.json" ):
with open( "Example_Data.json" ) as f:
all_items = json.load(f)
for text in all_items.get('A', []):
self.example_a.ui_listview.addItem(text)
for text in all_items.get('B', []):
self.example_b.ui_listview.addItem(text)
Also, in general, it's usually bad design for a parent widget to access grandchild widgets directly (ui_listview is a grandchild of your main widget ExampleMain class). It's generally better form for your widgets to define some type of interface for portraying what they need saved and loaded.
class ExampleMain:
def save_data(self):
data = {}
data['example_a'] = self.example_a.save_data()
data['example_b'] = self.example_b.save_data()
# Save to file
def load_data(self):
data = ... # read from file
self.example_a.load_data(data.get('example_a'))
self.example_b.load_data(data.get('example_b'))
class ExampleA:
def save_data(self):
data = []
for i in range(self.ui_listview.count()):
text = self.ui_listview.item(i).text()
data.append(text)
return data
def load_data(self, data):
for text in data:
self.ui_listview.addItem(text)

Categories

Resources