PyQt4: Save a QListWidget - python

I'm new in PyQt4.
I have a QListWidget, and then i would like to saveit directly but the only example i find is a a textedit and need to open a file first.
But in my case there is no file to open.
is it possible to do it?
so far my code looks like this:
def initUI(self):
self.edit = QtGui.QListWidget()
btn1 = QtGui.QPushButton("Check")
btn2 = QtGui.QPushButton("Quit")
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.closeEvent)
toolBar = QtGui.QToolBar()
fileButton = QtGui.QToolButton()
fileButton.setText('File')
fileButton.setMenu(self.menu())
saveButton = QtGui.QToolButton()
saveButton .setText('save')
saveButton .clicked.connect(self.save_menu)
toolBar.addWidget(fileButton)
toolBar.addWidget(saveButton )
def save_menu(self):
fn = QtGui.QFileDialog.getSaveFileName(self, "Save as...", '.',
"ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)")
self.setCurrentFileName(fn)
return self.fileSave()

Assuming you just want to save the text entries in your list, this should work. Beware that it will try and write a file to your disk.
import sys
import os
from PyQt4 import QtGui
class AnExample(QtGui.QMainWindow):
def __init__(self):
super(AnExample, self).__init__()
self.buildUi()
def buildUi(self):
self.listWidget = QtGui.QListWidget()
self.listWidget.addItems(['one',
'two',
'three'])
warning = QtGui.QLabel("Warning, this progam can write to disk!")
saveButton = QtGui.QPushButton('Save to location...')
justSaveButton = QtGui.QPushButton('Just save!')
saveButton.clicked.connect(self.onSave)
justSaveButton.clicked.connect(self.onJustSave)
grid = QtGui.QGridLayout()
grid.addWidget(warning, 0, 0)
grid.addWidget(self.listWidget, 1, 0)
grid.addWidget(saveButton, 2, 0)
grid.addWidget(justSaveButton, 3, 0)
central = QtGui.QWidget()
central.setLayout(grid)
self.setCentralWidget(central)
def onSave(self):
self.saveFile(True)
def onJustSave(self):
self.saveFile(False)
def saveFile(self, showDialog):
"""
Function that will save list items to file.
"""
# save to TESTING.txt in current working directory
savePath = os.path.join(os.getcwd(),
'TESTING.txt')
# allow user to override location if requested
if showDialog:
savePath = QtGui.QFileDialog.getSaveFileName(self,
'Save text file',
savePath,
'TESTING.txt')
# if just saving, or user didn't cancel, make and save file
if len(savePath) > 0:
with open(savePath, 'w') as theFile:
for i in xrange(self.listWidget.count()):
theFile.write(''.join([str(self.listWidget.item(i).text()),
'\n']))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = AnExample()
ex.show()
sys.exit(app.exec_())

Related

How can I use the Font Widget from PyQt in my text editor?

I'm having trouble in adding using the Font Widget from PyQt4 in my text editor. When I try to click the Font option it gives me this error:
File "directory", line 230, in FontFamily
self.text.setCurrentFont(font)
TypeError: setCurrentFont(self, QFont): argument 1 has unexpected type 'bool'
and when I try to click the Font Size option it gives me this error:
QFont::setPointSizeF: Point size <= 0 (0.000000), must be greater than 0
Here is my code:
#Imports
import sys, os
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QColumnView, QFileSystemModel, QSplitter, QTreeView
from PyQt4.QtCore import Qt, QDir
class Window(QtGui.QMainWindow):
#Window Settings
def __init__(self):
super(Window, self).__init__()
self.showMaximized()
self.setWindowTitle("Editory")
self.setWindowIcon(QtGui.QIcon('icons/favicon.png'))
#Text Window
self.text = QtGui.QTextEdit(self)
self.text.setTabStopWidth(12)
self.setCentralWidget(self.text)
# Font variables
fontBox = QtGui.QFontComboBox(self)
fontBox.currentFontChanged.connect(self.FontFamily)
fontSize = QtGui.QComboBox(self)
fontSize.setEditable(True)
# Minimum number of chars displayed
fontSize.setMinimumContentsLength(3)
fontSize.activated.connect(self.FontSize)
# Font Sizes
fontSizes = ['6','7','8','9','10','11','12','13','14',
'15','16','18','20','22','24','26','28',
'32','36','40','44','48','54','60','66',
'72','80','88','96']
for i in fontSizes:
fontSize.addItem(i)
#New Input
new = QtGui.QAction("&New", self)
new.setShortcut("Ctrl+N")
new.triggered.connect(self.New)
#Open Input
open = QtGui.QAction("&Open", self)
open.setShortcut("Ctrl+O")
open.triggered.connect(self.Open)
#Save Input
save = QtGui.QAction("&Save", self)
save.setShortcut("Ctrl+S")
save.triggered.connect(self.Save)
#Print Input
prints = QtGui.QAction("&Print", self)
prints.setShortcut("Ctrl+P")
prints.triggered.connect(self.Print)
#Quit Input
quit = QtGui.QAction("&Quit", self)
quit.setShortcut("Ctrl+Q")
quit.triggered.connect(self.Quit)
self.statusBar()
#Menubar
menubar = self.menuBar()
#File Menu
file = menubar.addMenu('&File')
#File Inputs
file.addAction(new)
file.addAction(open)
file.addAction(save)
file.addAction(prints)
file.addSeparator()
file.addAction(quit)
#Cut Input
cut = QtGui.QAction("&Cut", self)
cut.setShortcut("Ctrl+X")
cut.triggered.connect(self.Cut)
#Copy Input
copy = QtGui.QAction("&Copy", self)
copy.setShortcut("Ctrl+C")
copy.triggered.connect(self.Copy)
#Paste Input
paste = QtGui.QAction("&Paste", self)
paste.setShortcut("Ctrl+V")
paste.triggered.connect(self.Paste)
#Undo Input
undo = QtGui.QAction("&Undo", self)
undo.setShortcut("Ctrl+Z")
undo.triggered.connect(self.Undo)
#Redo Input
redo = QtGui.QAction("&Redo", self)
redo.setShortcut("Ctrl+Y")
redo.triggered.connect(self.Redo)
#Edit Menubar
edit = menubar.addMenu('&Edit')
#Edit Inputs
edit.addAction(cut)
edit.addAction(copy)
edit.addAction(paste)
edit.addSeparator()
edit.addAction(undo)
edit.addAction(redo)
#Fullscreen Input
fullscreen = QtGui.QAction("&Fullscreen", self)
fullscreen.setShortcut("F11")
fullscreen.triggered.connect(self.Fullscreen)
#Align Left Input
align_left = QtGui.QAction("&Align Left", self)
align_left.triggered.connect(self.Align_Left)
#Align Right Input
align_right = QtGui.QAction("&Align Right", self)
align_right.triggered.connect(self.Align_Right)
#Align Center Input
align_center = QtGui.QAction("&Align Center", self)
align_center.triggered.connect(self.Align_Center)
#Align Justify Input
align_justify = QtGui.QAction("&Align Justify", self)
align_justify.triggered.connect(self.Align_Justify)
#View Menubar
view = menubar.addMenu('&View')
#View Inputs
view.addAction(fullscreen)
view.addSeparator()
view.addAction(align_left)
view.addAction(align_right)
view.addAction(align_center)
view.addAction(align_justify)
#Font Family Input
font_family = QtGui.QAction("&Font", self)
font_family.triggered.connect(self.FontFamily)
#Font Size Input
font_size = QtGui.QAction("&Font Size", self)
font_size.triggered.connect(self.FontSize)
#Settings Menubar
settings = menubar.addMenu('&Settings')
#Settings Inputs
settings.addAction(font_family)
settings.addAction(font_size)
#Imports Toolbar
self.toolbar()
#Input Functions
def New(self):
self.text.clear()
def Open(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
f = open(filename, 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
def Save(self):
name = QtGui.QFileDialog.getSaveFileName(self, 'Save File')
file = open(name,'w')
text = self.textEdit.toPlainText()
file.write(text)
file.close()
def Print(self):
print_dialog = QtGui.QPrintDialog()
if print_dialog.exec_() == QtGui.QDialog.Accepted:
self.text.document().print_(print_dialog.printer())
def Quit(self):
sys.exit()
def Undo(self):
self.text.undo()
def Redo(self):
self.text.redo()
def Cut(self):
self.text.cut()
def Copy(self):
self.text.copy()
def Paste(self):
self.text.paste()
def Align_Left(self):
self.text.setAlignment(Qt.AlignLeft)
def Align_Right(self):
self.text.setAlignment(Qt.AlignRight)
def Align_Center(self):
self.text.setAlignment(Qt.AlignCenter)
def Align_Justify(self):
self.text.setAlignment(Qt.AlignJustify)
def Fullscreen(self):
if not self.isFullScreen():
self.showFullScreen()
else:
self.showMaximized()
def FontFamily(self,font):
self.text.setCurrentFont(font)
def FontSize(self, fontsize):
self.text.setFontPointSize(int(fontsize))
#Toolbar
def toolbar(self):
#New Tool
new = QtGui.QAction(QtGui.QIcon('icons/new.png'), 'New', self)
new.triggered.connect(self.New)
#Open Tool
open = QtGui.QAction(QtGui.QIcon('icons/open.png'), 'Open', self)
open.triggered.connect(self.Open)
#Save Tool
save = QtGui.QAction(QtGui.QIcon('icons/save.png'), 'Save', self)
save.triggered.connect(self.Save)
#Print Tool
prints = QtGui.QAction(QtGui.QIcon('icons/print.png'), 'Print', self)
prints.triggered.connect(self.Print)
#Quit Tool
quit = QtGui.QAction(QtGui.QIcon('icons/quit.png'), 'Quit', self)
quit.triggered.connect(self.Quit)
#Cut Tool
cut = QtGui.QAction(QtGui.QIcon('icons/cut.png'), 'Cut', self)
cut.triggered.connect(self.Cut)
#Copy Tool
copy = QtGui.QAction(QtGui.QIcon('icons/copy.png'), 'Copy', self)
copy.triggered.connect(self.Copy)
#Paste Tool
paste = QtGui.QAction(QtGui.QIcon('icons/paste.png'), 'Paste', self)
paste.triggered.connect(self.Paste)
#Undo Tool
undo = QtGui.QAction(QtGui.QIcon('icons/undo.png'), 'Undo', self)
undo.triggered.connect(self.Undo)
#Redo Tool
redo = QtGui.QAction(QtGui.QIcon('icons/redo.png'), 'Redo', self)
redo.triggered.connect(self.Redo)
#Toolbar Menu
self.toolbar = self.addToolBar("Toolbar")
self.toolbar.addAction(new)
self.toolbar.addAction(open)
self.toolbar.addAction(save)
self.toolbar.addSeparator()
self.toolbar.addAction(cut)
self.toolbar.addAction(copy)
self.toolbar.addAction(paste)
self.toolbar.addSeparator()
self.toolbar.addAction(undo)
self.toolbar.addAction(redo)
self.toolbar.addSeparator()
self.toolbar.addAction(prints)
self.toolbar.addSeparator()
self.toolbar.addAction(quit)
#Reveals The Toolbar
self.show()
#Run Function
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()
The problem is that initially you connect to the QFontComboBox and QComBoBox correctly:
...
fontBox.currentFontChanged.connect(self.FontFamily)
...
fontSize.activated.connect(self.FontSize)
but then you connect the triggered signals with the same functions, and since the combobox is never seen, only the triggered signal is emited:
font_family = QtGui.QAction("&Font", self)
font_family.triggered.connect(self.FontFamily)
#Font Size Input
font_size = QtGui.QAction("&Font Size", self)
font_size.triggered.connect(self.FontSize)
What you must do is that the Settings menu must have 2 sub-menus that open the QFontComboBox and QComboBox widgets, respectively, but to include these widgets in the submenus you must use QWidgetAction:
class Window(QtGui.QMainWindow):
#Window Settings
def __init__(self):
...
#Font Family Input
#Settings Menubar
settings = menubar.addMenu('&Settings')
menu_font = settings.addMenu("&Font")
font_family = QtGui.QWidgetAction(self)
font_family.setDefaultWidget(fontBox)
menu_font.addAction(font_family)
font_size = QtGui.QWidgetAction(self)
font_size.setDefaultWidget(fontSize)
menu_size = settings.addMenu("&Font Size")
menu_size.addAction(font_size)
self.toolbar()
...

PyQt: How convert my script to GUI?

I'm following this tutorial for a PyQt5 GUI window:
Here's My code on pastebin.
import sys
from PyQt5 import QtWidgets, QtGui
def window1():
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
b = QtWidgets.QPushButton('Comparison Report', w)
l1 = QtWidgets.QLabel(w)
l2 = QtWidgets.QLabel(w)
l1.setText('Main Page')
b.setGeometry(200, 100, 300, 70)
w.setWindowTitle('Diff Util')
w.setGeometry(800, 200, 720, 800)
l1.move(310, 5)
w.show()
sys.exit(app.exec_())
#import file_report
#def on_click(self):
#file_report()
window1()
Here's a comparison file script also on pastebin... but i Need 10rep to link it >_>
import sys
import os
import difflib
first_file = input("Select original file: ")
second_file = input("Select second file for comparison: ")
first_file_lines = open(first_file).readlines()
second_file_lines = open(second_file).readlines()
difference = difflib.HtmlDiff(tabsize=8,
wrapcolumn=100).make_file(first_file_lines, second_file_lines, first_file, second_file, charset='utf-8')
difference_report = open('difference_report.html', 'w')
difference_report.write(difference)
difference_report.close()
os.startfile('difference_report.html')
My question is, how to connect my file_report.py to the pushbutton I've created with PyQt5?
As you can see I commented out "import file_report" because from my understanding I'm supposed to import my script... but the import causes it to run the script in terminal, and after execution will open my GUI. I would like to run this script, but contain it within the GUI window I've created instead of opening a terminal for execution.
So where in the PyQt5 script should I import, and include the .py file?
GUIs are not friendly with blocking tasks since for their existence they create a loop. Therefore the function input() should not be used, the solution to use elements provided by the library as QLineEdit, PyQt also provides dialog boxes for the selection of files.
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
import difflib
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setLayout(QtWidgets.QGridLayout())
self.le1 = QtWidgets.QLineEdit("", self)
self.le2 = QtWidgets.QLineEdit("", self)
self.le3 = QtWidgets.QLineEdit("", self)
self.btn1 = QtWidgets.QPushButton("Select first file")
self.btn2 = QtWidgets.QPushButton("Select second file")
self.btn3 = QtWidgets.QPushButton("Select save File")
self.btnRun = QtWidgets.QPushButton("Run")
self.layout().addWidget(self.le1, 1, 1)
self.layout().addWidget(self.le2, 2, 1)
self.layout().addWidget(self.le3, 3, 1)
self.layout().addWidget(self.btn1, 1, 2)
self.layout().addWidget(self.btn2, 2, 2)
self.layout().addWidget(self.btn3, 3, 2)
self.layout().addWidget(self.btnRun, 4, 2)
self.btnRun.clicked.connect(self.onRun)
self.btn1.clicked.connect(self.selectFirstFile)
self.btn2.clicked.connect(self.selectSecondFile)
self.btn3.clicked.connect(self.selectSaveFile)
def selectFirstFile(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select Files", QtCore.QDir.currentPath(), "*.html")
if filename != "":
self.le1.setText(filename)
def selectSecondFile(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select Files", QtCore.QDir.currentPath(), "*.html")
if filename != "":
self.le2.setText(filename)
def selectSaveFile(self):
filename, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Select Files", QtCore.QDir.currentPath(), "*.html")
if filename != "":
self.le3.setText(filename)
def onRun(self):
first_file = self.le1.text()
second_file = self.le2.text()
output_file = self.le3.text()
first_file_lines = open(first_file).readlines()
second_file_lines = open(second_file).readlines()
difference = difflib.HtmlDiff(tabsize=8, wrapcolumn=100).make_file(first_file_lines, second_file_lines, first_file, second_file, charset='utf-8')
difference_report = open(output_file, 'w')
difference_report.write(difference)
difference_report.close()
QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(output_file))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

PyQt5 - Clicking Cancel on QFileDialog Closes Application

I've noticed that, using the following code, if you choose to click "Cancel" on the FileDialog for "Import File", the entire application closes instead of returning to the menu and awaiting a different choice. How can I get it to just return to the mainMenu?
(Note: I've noticed if I don't put anything after the initial file dialog call, it functions fine.)
Code:
import sys
import xml.etree.ElementTree as et
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MainMenu(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QGridLayout()
# Create Objects for Main Menu
logoLabel = QLabel("TESTAPP")
logoFont = QFont("Broadway", 48)
logoLabel.setFont(logoFont)
versionLabel = QLabel("Version 0.1a")
copyrightLabel = QLabel("Copyright 2016")
importButton = QPushButton("Import File")
quitButton = QPushButton("Quit")
# Set Locations of Widgets
layout.addWidget(logoLabel, 0, 0)
layout.addWidget(versionLabel, 1, 0)
layout.addWidget(copyrightLabel, 2, 0)
layout.addWidget(importButton, 4, 0)
layout.addWidget(quitButton, 5, 0)
self.setLayout(layout)
self.setWindowTitle("NESSQL")
# Connect Buttons to Actions
importButton.clicked.connect(self.importFile)
quitButton.clicked.connect(self.close)
def importFile(self):
# Open dialog box to get the filename
file = QFileDialog.getOpenFileName(self, caption="File to Import", directory=".",
filter="All Files (*.*)")
data = et.parse(file)
root = data.getroot()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = MainMenu()
mainMenu.show()
app.exec_()
by keeping condition for checking whether file is empty or not you can avoid this issue.
It goes something like this in your case.
def importFile(self):
# Open dialog box to get the filename
file = QFileDialog.getOpenFileName(self, caption="File to Import",
directory=".",filter="All Files (*.*)")
if not file[0] == "":
data = et.parse(file)
root = data.getroot()
saran vaddi's answer didn't work for me but this did:
def importFile(self):
# Open dialog box to get the filename
file = QFileDialog.getOpenFileName(self, caption="File to Import", directory=".", filter="All Files (*.*)")
# If file is blank, simply return control to calling function
if not file:
return

How to create a button for each element in a list and put it in a scroll-area?

I have a list which gets one element each time user opens a file. I need to create a button with the file's name (element from the list), each time this file is appended to a list, and put this button into a scroll-area.
The problem is that I always have only one button, that just changes its name:
filenames = []
def addfiles():
fileName = QtGui.QFileDialog.getOpenFileName()
fileDirectory = unicode(fileName)
global filenames
filenames.append(fileDirectory)
button = QtGui.QPushButton(os.path.basename(fileDirectory))
window.scrollArea.setWidget(button)
I know that the problem is that I add the same object (button) to the scroll-area, but I don't know how to fix it.
The Problem is not that you add the same button, but that you sort of replace the Widget in the scrollArea.
A better way would be to create a QHBoxLayout and than add the buttons to the layout.
filenames = []
lay = QtGui.QHboxLayout()
window.scrollArea.setLayout(lay)
def addfiles():
fileName= QtGui.QFileDialog.getOpenFileName()
fileDirectory = unicode(fileName)
global filenames
filenames.append(fileDirectory)
button = QtGui.QPushButton(os.path.basename(fileDirectory))
lay.addWidget(button)
In a sort of that way it should work. Here is a small working example:
from PyQt4 import QtGui
import sys
filenames = []
class TestGui(QtGui.QWidget):
""" A Fast test gui show how to create buttons in a ScrollArea"""
def __init__(self):
super(TestGui, self).__init__()
self.lay = QtGui.QHBoxLayout()
self.sA = QtGui.QScrollArea()
self.sA_lay = QtGui.QVBoxLayout()
self.sA.setLayout(self.sA_lay)
self.closeGui = QtGui.QPushButton("Close")
self.add_file_button = QtGui.QPushButton("Add File")
self.lay.addWidget(self.closeGui)
self.lay.addWidget(self.add_file_button)
self.lay.addWidget(self.sA)
self.setLayout(self.lay)
self.connect_()
self.show()
def connect_(self):
self.add_file_button.clicked.connect(self.__add_file_to_list)
self.closeGui.clicked.connect(self.close)
return
def __add_file_to_list(self):
fname = QtGui.QFileDialog.getOpenFileName()
global filenames
filenames.append(fname)
button = QtGui.QPushButton(fname)
self.sA_lay.addWidget(button)
return
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
tg = TestGui()
sys.exit(app.exec_())
The problem is that you're not adding a layout to the scrollLayout, you're setting the scrollArea's widget:
#!/usr/bin/env python
import os, sys
from PyQt4 import QtCore, QtGui
filenames = []
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.centralwidget = QtGui.QWidget(self)
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout.addWidget(self.scrollArea)
self.setCentralWidget(self.centralwidget)
# create a layout for your scrollarea
self.formLayout = QtGui.QFormLayout(self.scrollAreaWidgetContents)
self.addFiles()
def addFiles(self):
global filenames
filenames.append("~/files/newFile.txt")
button = QtGui.QPushButton(os.path.basename(filenames[-1]))
self.formLayout.addWidget(button)

Fill a QListWidget using getOpenFileNames

In the example below, I would like to fill my QListWidget with files opening a Qdialog. I don't understand how I can add the files selected in the list. Should I do a new class? How can I connect the two methods setupList and addFiles?
import sys
from PyQt4 import QtCore, QtGui
from datapath import *
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.sources =[]
self.setupActions()
self.setupList()
self.setupUi()
self.setupStatusBars()
def addFiles(self):
files = QtGui.QFileDialog.getOpenFileNames(
self,"Open File", dirpath, "txt Files (*.txt)")
for string in files:
self.sources.append(str(string))
return self.sources
def setupActions(self):
self.exitAct = QtGui.QAction(
QtGui.QIcon(':/images/exit.png'),
"E&xit", self, shortcut="Ctrl+Q",
statusTip="Exit the application", triggered=self.close
)
self.addFilesAct = QtGui.QAction(
QtGui.QIcon(':/images/open.png'),
"Add &Files", self, shortcut=QtGui.QKeySequence.Open,
statusTip="Open an existing file", triggered=self.addFiles
)
def setupList(self):
#FileList
self.FileList = QtGui.QListWidget(self)
self.FileList.addItems(self.sources)
def setupUi(self):
#Window size
horiz = 300
vert = 300
self.setGeometry(self.width()/2, self.height()/2,horiz,vert)
self.setWindowTitle("test")
#MenuBar
self.FileMenu = self.menuBar().addMenu("&File")
self.FileMenu.addAction(self.addFilesAct)
self.FileMenu.addSeparator();
self.FileMenu.addAction(self.exitAct)
#ToolBar
self.fileToolBar = self.addToolBar("Open")
self.fileToolBar.addAction(self.addFilesAct)
self.fileToolBar.setIconSize(QtCore.QSize(64,64))
#Build Layout
mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(self.FileList)
widget = QtGui.QWidget()
widget.setLayout(mainLayout)
self.setCentralWidget(widget)
def setupStatusBars(self):
self.statusBar().showMessage("Ready")
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When self.sources is changed, the elements of the QListWidget will not change. So self.FileList.addItems(self.sources) in setupList() should be removed and instead put in addFiles() so that every time the files are selected in the dialog, the QListWidget's addItems method is called. Then return self.sources in addFiles() would be unnecessary.
In order to append files to the listwidget, the addFiles method should look like this:
def addFiles(self):
files = QtGui.QFileDialog.getOpenFileNames(
self, "Open File", dirpath, "txt Files (*.txt)")
for string in files:
self.FileList.addItem(string)
The source list looks like it might be redundant. If you need to get the full list of files, you can do something like this:
sources = []
for row in range(self.FileList.count()):
item = self.FileList.item(row)
# python3
sources.append(item.text())
# python2, convert to python strings
# sources.append(unicode(item.text()))
print(sources)

Categories