PyQt5: How to input default value if QLineEdit is empty? - python

I have already associated my PyQt5 Gui with Excel.
I would like to input '2000' into Excel via PyQt5 Gui program even if I do not input anything on it.
The explanation photo is below:
even if I do not input anything in PyQt5 Gui,
'2000' should be typed in Excel.
However, the point is if anything input in PyQt5 Gui, it should be written in Excel as it was written on PyQt5.
The code that I made is below:
class Ship_Use_Tug_Input_Program(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
visbl = QLabel('Visibility(m)', self)
visbl.move(60, 450)
vis_ent = QLineEdit(self)
vis_ent.move(180, 445)
file = pathlib.Path('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
if file.exists():
pass
else:
file=Workbook()
sheet = file.active
file.save('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
def save_to_excel(self):
file = openpyxl.load_workbook('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
sheet = file.active
sheet.cell(column=10, row=sheet.max_row, value=vis_ent.text())
file.save('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
btn_save = QPushButton('S a v e', self)
btn_save.clicked.connect(save_to_excel)
btn_save.move(400,510)
self.setWindowTitle('Ship use tug input program')
self.setFixedSize(945, 570)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Ship_Use_Tug_Input_Program()
sys.exit(app.exec_())

You should always add widgets as attributes, so you can access them in other methods:
class Ship_Use_Tug_Input_Program(QWidget):
...
def initUI(self):
self.visbl = QLabel('Visibility(m)', self)
self.visbl.move(60, 450)
self.vis_ent = QLineEdit(self)
self.vis_ent.move(180, 445)
Now you can get the input text:
def save_to_excel(self):
...
sheet = file.active
value = self.vis_ent.text().strip() or '2000'
sheet.cell(column=10, row=sheet.max_row, value=value)
...
If vis_ent is empty or whitespace-only, the default value will be used instead.
UPDATE:
Here is what your whole class should look like:
class Ship_Use_Tug_Input_Program(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.visbl = QLabel('Visibility(m)', self)
self.visbl.move(60, 450)
self.vis_ent = QLineEdit(self)
self.vis_ent.move(180, 445)
self.btn_save = QPushButton('S a v e', self)
self.btn_save.clicked.connect(self.save_to_excel)
self.btn_save.move(400, 510)
self.setWindowTitle('Ship use tug input program')
self.setFixedSize(945, 570)
self.show()
file = pathlib.Path('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
if file.exists():
pass
else:
file=Workbook()
sheet = file.active
file.save('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
def save_to_excel(self):
file = openpyxl.load_workbook('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')
sheet = file.active
value = self.vis_ent.text().strip() or '2000'
sheet.cell(column=10, row=sheet.max_row, value=value)
file.save('C:/Users/woody/OneDrive/Desktop/Python Workspace/Ship_Use_Tug_Input_Program.xlsx')

Related

How can I update a figure when button is pressed in a different class in PyQt5?

I am building a GUI in python using PyQt5. Data is imported using on_pushButtonLoad_clicked() and get_file() located in TabWidget.
My goal is to:
transfer this data (importedfile) to FirstTab()
update the plot MRChart(importedfile) using the recently imported data.
I have completed the first goal in transferring the data to FirstTab() whereby the plot is generated and can be shown (for demonstrative purposes) in the browser using fig.show(). Although MRChart(importedfile) is connected to the plotting widget energy() by self.browser, the figure fails to show in the GUI.
Code:
class TabWidget(QDialog):
def __init__(self, data):
super(TabWidget, self).__init__()
self.data = data
self.showMaximized()
#create filter object
FilterLayout = QHBoxLayout()
FilterLayout.addWidget(self.createHeader1a(), 2)#column width
#create tab widget object
tabwidget = QTabWidget()
tabwidget.addTab(FirstTab(self.data), "Tab 1")
vbox = QVBoxLayout()
vbox.addLayout(FilterLayout)
vbox.addWidget(tabwidget)
self.setLayout(vbox)
def createHeader1a(self): # function defining characteristics of each group/grid object
HeaderBox = QGroupBox("Import Data")
inputfilebtn = QPushButton("Import")
inputfilebtn.resize(150, 50)
inputfilebtn.clicked.connect(self.on_pushButtonLoad_clicked)
#importrow1
importrow1layout = QHBoxLayout()
importrow1layout.addWidget(inputfilebtn)
importrow1layout.addStretch()
HeaderLayout = QGridLayout()
HeaderLayout.addLayout(importrow1layout, 0, 1)
HeaderBox.setLayout(HeaderLayout)
HeaderBox.setFlat(True)
return HeaderBox
def getfile(self):
option = QFileDialog.Options()
fname = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\', "CSV files (*.csv)", options=option)
global importedfile
importedfile = pd.read_csv(fname[0])
#QtCore.pyqtSlot()
def on_pushButtonLoad_clicked(self):
self.getfile()
FT=FirstTab(data=importedfile)
FT.MRChart(importedfile)
class FirstTab(QWidget):
def __init__(self, data):
super(FirstTab, self).__init__()
self.data = data
# Grid layout of entire tab
layout = QGridLayout()
layout.addWidget(self.energy(), 3, 0)
layout.setRowStretch(3, 3)
layout.setColumnStretch(0, 1)
self.setLayout(layout)
def MRChart(self, importedfile): # pie
fig = go.Pie(labels=importedfile["Label1"], values=importedfile["Label2"])
layout = go.Layout(autosize=True, legend=dict(orientation="h",xanchor='center', x=0.5))# height = 600, width = 1000,
fig = go.Figure(data=fig, layout=layout)
fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
fig.show()# only included to prove that figure has been created
self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
def energy(self):
groupBox = QGroupBox("Box Title")
self.browser = QtWebEngineWidgets.QWebEngineView(self)
exportfilebtn = QCheckBox("tickbox1")
middleright = QHBoxLayout()
middleright.addWidget(self.browser)
middleright.addWidget(exportfilebtn)
groupBox.setLayout(middleright)
groupBox.setFlat(True)
return groupBox
if __name__ == "__main__":
app = QApplication(sys.argv)
tabwidget = TabWidget(data=None)
tabwidget.show()
app.exec()
Updated code in line with musicamante's answer
class TabWidget(QDialog):
def __init__(self, data):
super(TabWidget, self).__init__()
self.data = data
self.firstTab = FirstTab(self.data)
#create filter object
FilterLayout = QHBoxLayout()
FilterLayout.addWidget(self.createHeader1a(), 2)#column width
#create tab widget object
tabwidget = QTabWidget()
tabwidget.addTab(self.firstTab "Tab 1")
vbox = QVBoxLayout()
vbox.addLayout(FilterLayout)
vbox.addWidget(tabwidget)
self.setLayout(vbox)
def createHeader1a(self): # function defining characteristics of each group/grid object
HeaderBox = QGroupBox("Import Data")
inputfilebtn = QPushButton("Import")
inputfilebtn.resize(150, 50)
inputfilebtn.clicked.connect(self.on_pushButtonLoad_clicked)
#importrow1
importrow1layout = QHBoxLayout()
importrow1layout.addWidget(inputfilebtn)
importrow1layout.addStretch()
HeaderLayout = QGridLayout()
HeaderLayout.addLayout(importrow1layout, 0, 1)
HeaderBox.setLayout(HeaderLayout)
HeaderBox.setFlat(True)
return HeaderBox
def getfile(self):
option = QFileDialog.Options()
fname = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\', "CSV files (*.csv)", options=option)
return pd.read_csv(fname[0])
#QtCore.pyqtSlot()
def on_pushButtonLoad_clicked(self):
importedfile = self.getfile()
if importedfile is None:
return
self.firstTab.MRChart(importedfile)
class FirstTab(QWidget):
def __init__(self, data):
super(FirstTab, self).__init__()
self.data = data
# Grid layout of entire tab
layout = QGridLayout()
layout.addWidget(self.energy(), 3, 0)
layout.setRowStretch(3, 3)
layout.setColumnStretch(0, 1)
self.setLayout(layout)
def MRChart(self, importedfile): # pie
fig = go.Pie(labels=importedfile["Label1"], values=importedfile["Label2"])
layout = go.Layout(autosize=True, legend=dict(orientation="h",xanchor='center', x=0.5))# height = 600, width = 1000,
fig = go.Figure(data=fig, layout=layout)
fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
fig.show()# only included to provde figure is created
self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
def energy(self):
groupBox = QGroupBox("Box Title")
self.browser = QtWebEngineWidgets.QWebEngineView(self)
exportfilebtn = QCheckBox("tickbox1")
middleright = QHBoxLayout()
middleright.addWidget(self.browser)
middleright.addWidget(exportfilebtn)
groupBox.setLayout(middleright)
groupBox.setFlat(True)
return groupBox
if __name__ == "__main__":
app = QApplication(sys.argv)
tabwidget = TabWidget(data=None)
tabwidget.show()
app.exec()
You're creating a new instance of FirstTab, instead of using the existing one.
You must keep a reference to the first instance and then call its MRChart function.
Also, you should not use globals: getfile() should return the value, and you should use that returned value in on_pushButtonLoad_clicked.
class TabWidget(QDialog):
def __init__(self, data):
# ...
self.firstTab = FirstTab(self.data)
tabwidget.addTab(self.firstTab, "Tab 1")
# ...
def getfile(self):
option = QFileDialog.Options()
fname, _ = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\', "CSV files (*.csv)", options=option)
if fname:
return pd.read_csv(fname)
#QtCore.pyqtSlot()
def on_pushButtonLoad_clicked(self):
importedfile = self.getfile()
if importedfile is None:
return
self.firstTab.MRChart(importedfile)
Note that it's good practice to show the window only after adding its elements, and it's also usually better to not call show*() in the __init__. It's also pointless to use resize() on a widget that is being added to a layout.

Add/Remove layout containing multiple widgets pyqt

I'm trying to make a gui that allows the addition/removal of multiple QtWidgets. The user selects a file and has the option off adding a comment in the lineedit next to it. A quick search on this site has so far given me the following code which allows me to add rows widgets.
import os
import sys
from PyQt5 import QtGui, QtCore, QtWidgets
class Additional(QtWidgets.QMainWindow):
def __init__(self):
super(Additional, self).__init__()
self.addButton = QtWidgets.QPushButton(' + ')
self.delButton = QtWidgets.QPushButton(' - ')
self.acceptButton = QtWidgets.QPushButton('Accept')
self.cancelButton = QtWidgets.QPushButton('Cancel')
self.addButton.clicked.connect(self.addWidget)
self.delButton.clicked.connect(self.delWidget)
self.acceptButton.clicked.connect(self.acceptValues)
self.cancelButton.clicked.connect(self.cancel)
self.scrollLayout = QtWidgets.QFormLayout()
self.scrollWidget = QtWidgets.QWidget()
self.scrollWidget.setLayout(self.scrollLayout)
self.scrollArea = QtWidgets.QScrollArea()
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.scrollWidget)
self.button_layout = QtWidgets.QVBoxLayout()
self.mainLayout = QtWidgets.QHBoxLayout()
self.button_layout.addWidget(self.addButton)
self.button_layout.addWidget(self.delButton)
self.button_layout.addWidget(self.acceptButton)
self.button_layout.addWidget(self.cancelButton)
self.mainLayout.addLayout(self.button_layout)
self.mainLayout.addWidget(self.scrollArea)
self.centralWidget = QtWidgets.QWidget()
self.centralWidget.setLayout(self.mainLayout)
self.setCentralWidget(self.centralWidget)
self.resize(800, 200)
self.setFixedSize(self.size())
self.show()
def addWidget(self):
self.scrollLayout.addRow(AddRow())
def delWidget(self):
# Would this call another class to remove the row? If so, how?
pass
def acceptValues(self):
# Would I count the widgets in the 'scroll' area and get the data from that?
pass
def cancel(self):
QtCore.QCoreApplication.instance().quit()
# BTW, is this the right way to close the window/instance?
class AddRow(QtWidgets.QWidget):
def __init__( self, parent=None):
super(AddRow, self).__init__(parent)
self.button = QtWidgets.QPushButton('Select file')
self.label = QtWidgets.QLabel('Selection will go here')
self.lineedit = QtWidgets.QLineEdit()
self.lineedit.setPlaceholderText("Rename (optional)...")
# Would I add the button callback here?
layout = QtWidgets.QHBoxLayout()
layout.addWidget(self.button)
layout.addWidget(self.label)
layout.addWidget(self.lineedit)
self.setLayout(layout)
app = QtWidgets.QApplication(sys.argv)
myApp = Additional()
app.exec_()
I'm trying to figure out:
How to delete the last row that's been added.
How to assign the action to the button (this be done in the 'AddRow'
class likeself.buttton.clicked.callback(self.selectfile)
How to collect the data from the rows (ie, after 'accept' has been
clicked)
Any ideas would be welcome!
Before pointing to the solution, I'm just going to change the name of the AddRow class to RowWidget because a class should not indicate action.
class RowWidget(QtWidgets.QWidget):
def __init__( self, parent=None):
super(RowWidget, self).__init__(parent)
...
How to delete the last row that's been added ?
Since you are using QFormLayout and assuming that you are using a version PyQt5>=5.8 you can use the removeRow() method:
#QtCore.pyqtSlot()
def delWidget(self):
if self.scrollLayout.rowCount() > 0:
self.scrollLayout.removeRow(self.scrollLayout.rowCount()-1)
How to assign the action to the button (this be done in the 'AddRow' class likeself.buttton.clicked.callback(self.selectfile)?
Each part of your application must be independent so the slot that you select the file must be part only of RowWidget, and RowWidget must have a method that returns that value:
class RowWidget(QtWidgets.QWidget):
def __init__( self, parent=None):
super(RowWidget, self).__init__(parent)
self.button = QtWidgets.QPushButton('Select file')
self.label = QtWidgets.QLabel('Selection will go here')
self.lineedit = QtWidgets.QLineEdit()
self.lineedit.setPlaceholderText("Rename (optional)...")
self.button.clicked.connect(self.on_select_file)
layout = QtWidgets.QHBoxLayout(self)
layout.addWidget(self.button)
layout.addWidget(self.label)
layout.addWidget(self.lineedit)
#QtCore.pyqtSlot()
def on_select_file(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File")
if filename:
self.lineedit.setText(filename)
def get_filename(self):
return self.lineedit.text()
How to collect the data from the rows (ie, after 'accept' has been clicked)?
The widgets attached to a layout are children of the widget where the layout has been added, that widget can be obtained through parentWidget(), having that parent we can obtain their children through findChildren():
#QtCore.pyqtSlot()
def acceptValues(self):
l_values = []
for w in self.scrollLayout.parentWidget().findChildren(RowWidget):
l_values.append(w.get_filename())
print(l_values)
The previous method may fail if the parentWidget() has other children that belong to RowWidget.
Another option, and that does not fail is to iterate through the QLayoutItems:
#QtCore.pyqtSlot()
def acceptValues(self):
l_values = []
for i in range(self.scrollLayout.rowCount()):
layout_item = self.scrollLayout.itemAt(i)
if isinstance(layout_item.widget(), RowWidget):
l_values.append(layout_item.widget().get_filename())
print(l_values)

Get text from FileDialog Python\Qt

I'm pretty new with Qt in Python, and I need to know how could I get from a file dialog one directory path and show it in a text box inside my ui.
class ControllerLibraryUI(QtWidgets.QDialog):
def __init__(self):
super(ControllerLibraryUI, self).__init__()
self.setWindowTitle('Controller Window')
self.buildUI()
def buildUI(self):
layout = QtWidgets.QVBoxLayout(self)
textWidget = QtWidgets.QWidget()
textLayout = QtWidgets.QHBoxLayout(textWidget)
layout.addWidget(textWidget)
self.saveNameField = QtWidgets.QTextEdit()
textLayout.addWidget(self.saveNameField)
btnWidget = QtWidgets.QWidget()
btnLayout = QtWidgets.QHBoxLayout(btnWidget)
layout.addWidget(btnWidget)
importBtn = QtWidgets.QPushButton('Import')
importBtn.clicked.connect(self.load)
btnLayout.addWidget(importBtn)
closeBtn = QtWidgets.QPushButton('Close')
closeBtn.clicked.connect(self.close)
btnLayout.addWidget(closeBtn)
def load(self ):
filename = QtWidgets.QFileDialog.getOpenFileName()[0]
print filename
def showUI():
try:
ui.close()
except:
ui = ControllerLibraryUI()
ui.show()
return ui
ui = showUI()
This is the basic concept.
for the file dialog :
directory = QtGui.QFileDialog.getExistingDirectory(self, 'Select directory')
and then you assign the directory variable to the setText method from your text box

Get settings from child window in Pyside

I have a few questions.
How do i properly get settings from the child window when i press 'Print' button?
How do i close the Settings window and save/commit changes only when user presses 'OK' vs 'Cancel' which just closes the dialog and dismisses the changes.
Settings Window
import sys
from PySide import QtGui, QtCore
class SettingsWindow(QtGui.QDialog):
def __init__(self, parent=None):
super(SettingsWindow, self).__init__(parent)
self.resize(200, 150)
self.setWindowTitle('Settings')
self.initUI()
def initUI(self):
lb_max = QtGui.QLabel('Max')
self.ui_max = QtGui.QSpinBox()
self.ui_max.setValue(5)
lb_min = QtGui.QLabel('Min')
self.ui_min = QtGui.QSpinBox()
self.ui_min.setValue(10)
lb_count = QtGui.QLabel('Count')
self.ui_count = QtGui.QSpinBox()
self.ui_count.setValue(25)
self.buttons = QtGui.QDialogButtonBox();
self.buttons.setOrientation(QtCore.Qt.Horizontal)
self.buttons.setStandardButtons(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)
self.buttons.layout().setDirection(QtGui.QBoxLayout.LeftToRight)
grid = QtGui.QGridLayout()
grid.setContentsMargins(10,10,10,10)
grid.addWidget(lb_max,0,0)
grid.addWidget(self.ui_max,0,1)
grid.addWidget(lb_min,1,0)
grid.addWidget(self.ui_min,1,1)
grid.addWidget(lb_count,2,0)
grid.addWidget(self.ui_count,2,1)
grid.addWidget(self.buttons,3,1)
self.setLayout(grid)
Main Window
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(200, 150)
self.setWindowTitle('Assets')
self.initUI()
def initUI(self):
self.mi_settings = QtGui.QAction('Settings', self)
self.mi_settings.triggered.connect(self.open_settings)
self.ui_button = QtGui.QPushButton('Print')
self.ui_button.clicked.connect(self.clicked_button)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(self.mi_settings)
grid = QtGui.QVBoxLayout()
grid.setContentsMargins(10,10,10,10)
grid.addWidget(self.ui_button)
main_widget = QtGui.QWidget()
main_widget.setLayout(grid)
self.setCentralWidget(main_widget)
def open_settings(self):
win = SettingsWindow()
win.exec_()
def clicked_button(self):
print 'Settings'
print '\tMax: '
print '\tMin: '
print '\tCount: '
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = MainWindow()
# ex = SettingsWindow()
ex.show()
sys.exit(app.exec_())
Firstly, you need to connect up the buttons in the dialog, so that you can tell whether the user cancelled it or not:
class SettingsWindow(QtGui.QDialog):
...
def initUI(self):
...
self.buttons = QtGui.QDialogButtonBox()
...
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
Secondly, you should think about how you set the defaults in the dialog, and how you reset/retrieve the current values. One way to do this would be to have a central settings dictionary where you store the values, with the dialog being used to update it from user input:
class SettingsWindow(QtGui.QDialog):
...
def getValues(self):
return {
'max': self.ui_max.value(),
'min': self.ui_min.value(),
'count': self.ui_count.value(),
}
def setValues(self, settings):
self.ui_max.setValue(settings['max'])
self.ui_min.setValue(settings['min'])
self.ui_count.setValue(settings['count'])
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
...
# default values
self.settings = {
'max': 5,
'min': 10,
'count': 25,
}
def open_settings(self):
win = SettingsWindow()
# reset from current values
win.setValues(self.settings)
if win.exec_() == QtGui.QDialog.Accepted:
# update only if user clicked ok
self.settings.update(win.getValues())
def clicked_button(self):
print 'Settings:'
for key in 'max', 'min', 'count':
print '\t%s = %s' % (key.title(), self.settings[key])
There are numerous ways to solve this kind of problem, but this should give you the general idea.
You can check the result of the exec_() command to see whether the dialog was accepted or rejected. If it was accepted, you can read the values of the GUI controls
win = SettingsWindow()
r = win.exec_()
if r:
min_val = win.ui_min.value()
max_val = win.ui_max.value()
cnt_val = win.ui_max.value()

Creating a button for PyQT window at each loop

class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
self.initUI()
def initUI(self):
YDrive = QtGui.QAction(QtGui.QIcon('y.gif'), 'Exit', self)
SDrive = QtGui.QAction('S', self)
GDrive = QtGui.QAction('G', self)
AddDrive = QtGui.QAction('+', self)
YDrive.triggered.connect(self.setYDir)
SDrive.triggered.connect(self.setSDir)
GDrive.triggered.connect(self.setGDir)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(YDrive)
self.toolbar.addAction(SDrive)
self.toolbar.addAction(GDrive)
self.toolbar.addAction(AddDrive)
#btn1 = QtGui.QPushButton("Button 1", self)
#btn1.move(30, 50)
#btn2 = QtGui.QPushButton("Button 2", self)
#btn2.move(150, 50)
#btn1.clicked.connect(self.buttonClicked)
#btn2.clicked.connect(self.buttonClicked)
self.setGeometry(300, 300, 250, 150)
self.center()
self.setWindowTitle('Message box')
self.show()
def setYDir(self):
myInputs[1] = "Y"
print "myInputs[1] CHANGED to Y"
myWorkDrive = "Y:\\HoC_Jobs\\"
shows = self.listDirs(myWorkDrive)
for elements in shows:
btn1 = QtGui.QPushButton(elements, self)
btn1.move(30, 50)
btn1.clicked.connect(self.buttonClicked)
What I'm trying to do in the last loop in setYDir is create a button for each element in the list shows. However, it doesn't seem to be working right. It does not update the buttons depending on thebutton I click in the toolbar. Any help?
Well, if you add components to a parent widget without using a layout and after you've called show on the parent, you'll have to show the children yourself.
Also, all your buttons are overlapping, so you'll only see the last one added. When posting source it's always good to strip it down to the minimum required to run it. In this case that would look something like this:
from PyQt4 import QtGui
import os
class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
self.initUI()
def initUI(self):
YDrive = QtGui.QAction("Y", self)
YDrive.triggered.connect(self.setYDir)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(YDrive)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
self.show()
def buttonClicked(self):
print "clicked"
def setYDir(self):
myWorkDrive = "/tmp"
shows = os.listdir(myWorkDrive)
i = 0
for elements in shows:
btn1 = QtGui.QPushButton(elements, self)
btn1.move(30, 50 + i)
i += 30
btn1.clicked.connect(self.buttonClicked)
btn1.show()
self.resize(self.width(), 50 + i)
if __name__ == '__main__':
app = QtGui.QApplication([])
t = Test()
t.show()
app.exec_()

Categories

Resources