I am trying a couple of sample programs that are not working in the last image of Debian for BBB. They work in a regular Xubuntu 13.10 distribution ad on windows but I have not been able to identify why Qpixmap is not working on this image. The regular widgets work Ok but the Qpixmap is not showing the image. The pyqt version installed is the 4.9.
One of the examples that I am using is the following.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Imagen(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QtGui.QHBoxLayout(self)
pixmap = QtGui.QPixmap("test.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
hbox.addWidget(lbl)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Test')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Imagen()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Assuming that your png and python files are in the same directory add the following code:
Import os.path
import os.path as osp
add the following code to initUI()
...
path = osp.join(osp.direname(__file__), 'test.png')
pixmap = QtGui.QPixmap(path)
...
Relative paths are relative to the current directory, which is not necessarily the same as the directory the script itself is in. So either use an absolute pathname, or cd to the directory the image file is in before running the script.
However, if you're interested in solving this general issue properly, the best approach is to learn how to use the Qt Resource System and the pyrcc tool. This allows you to embed icons (or any files you like) directly in your application, and thus completely side-steps any potential problems with locating files.
Related
I have a fresh QtCreator installation, and I set it up to run using a fresh install of Python3.8 on which I pip-installed both pyside2 and pyside6.
When I create a new Qt for Python - Window (UI file) application, whatever I do to the UI file the window always shows up empty and with the default size when I run the app.
I've tried with a QDialog, QMainApplication, using Pyside2 or Pyside6, I've checked that it was correctly loading the UI (and the right one) - no dice. It just won't update, and appears not to have any reason not to.
Default code for completeness:
# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys
from PySide2.QtWidgets import QApplication, QDialog
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader
class Dialog(QDialog):
def __init__(self):
super(Dialog, self).__init__()
self.load_ui()
def load_ui(self):
loader = QUiLoader()
path = os.fspath(Path(__file__).resolve().parent / "form.ui")
ui_file = QFile(path)
ui_file.open(QFile.ReadOnly)
loader.load(ui_file, self)
ui_file.close()
if __name__ == "__main__":
app = QApplication([])
widget = Dialog()
widget.show()
sys.exit(app.exec_())
(In the UI I just drag-dropped a button right in the middle and saved the file)
Am I forgetting something fundamental? I'm only used to programming in C++ using QtCreator.
I was expecting this to work right out of the box, but it's not.
This only dynamically load the UI as a new widget, with this custom class as a parent.
If I want signals and slots to work, the only thing I've found was to add a custom build step:
Command: <path to pyside6 install, use pip show to know where>\uic.exe
Arguments: <filename of the .ui file> -o <the python translation .py
which will serve as baseclass> -g python
Working directory: [your project dir]
Then signals and slots need to be connected manually, so QtCreator really only enables you to draw the user interface but all the logic still needs to be done by hand. Component variables are normally named after their UI name, but you can see for yourself in the baseclass file. This is a big step back from how QtCreator is used in C++ ("go to slot" will not work).
Code to use:
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from YourGenPyFileName import Ui_YourUIName
class MainWindow(QMainWindow, Ui_YourUIName):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QApplication([])
widget = MainWindow()
widget.show()
sys.exit(app.exec_())
I am having trouble figuring out how to use Qt to create translation files for a python apllication.
I'm using python 2.7, Qt version 5.9.1 and PyQt4 4.12.1 to create my GUI on OSX 10.11.6.
For now I just wanted to translate a few words on my code.
For what I understand, I have to use QtLinguist to open a .ts file, translate the words and create a .qm file, which will then be used by python.
From Qt Linguist page I get that I need to use a .pro project file, that will be read by pylupdate4, etc...
Now, I do I create a .pro file?
I tried running:
$ qmake -project myfile.py
$ pylupdate4 myfile.pro -ts file.ts
but the resulting .pro file can't be read by pylupdate4 (XML error: Parse error at line 1, column 1 [...])
From this Tutorial, I tried:
$ pylupdate4 myfile.py -ts file.ts
Which creates an empty .ts file, that Qt Linguist can't open.
Can someone give my any tip on what might be wrong, the 15 tabs I have open in my browser are not helping.
Here's my python code if you need it:
import sys
import os.path as osp
import os
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow,self).__init__()
# Set MainWindow geometry, use settings of last session. If it's first session,
# use defaulted settings
self.settings = QtCore.QSettings('Paul',QtCore.QSettings.NativeFormat)
self.resize(self.settings.value("size", QtCore.QSize(500, 300)).toSize())
self.move(self.settings.value("pos", QtCore.QPoint(5, 5)).toPoint());
self.initUI()
def closeEvent(self, e):
#Save MainWindow geometry session when closing the window
self.settings.setValue("size",self.size())
self.settings.setValue("pos",self.pos())
e.accept()
def initUI(self):
self.hbox = QtGui.QVBoxLayout(self) # Create Vertival box layout to put the buttons
self.myButtons = QtGui.QPushButton('button',self) #create push button
self.myButtons.setStyleSheet("""QPushButton { background-color: red; font:bold 20px}""")
self.myButtons.setToolTip('Push this button')
self.myButtons.setText(self.tr(QtCore.QString('yes')))
comboBox=QtGui.QComboBox(self) #create drop down menu
comboBox.addItem('Portugues')
comboBox.addItem('English')
self.hbox.addWidget(comboBox,1,QtCore.Qt.AlignRight) #add drop down menu to box layout
self.hbox.addStretch(3) # set separation between buttons
self.myButtons.clicked.connect(self.buttonClicked) # what should the button do
self.hbox.addWidget(self.myButtons,1,QtCore.Qt.AlignRight) #add button to box layout
self.setWindowTitle('Test2')
self.show()
def buttonClicked(self):
msbox= QtGui.QMessageBox()
choice=msbox.warning(self,'ok',"This button doesn't do anything!!!")
if choice == QtGui.QMessageBox.No:
print('nanan')
else:
print('Bye')
self.settings.setValue("size",self.size());
self.settings.setValue("pos",self.pos());
sys.exit()
def main():
app = QtGui.QApplication(sys.argv)
translator = QtCore.QTranslator()
translator.load("~/basefiles/translations/qt_pt.qm")
app.installTranslator(translator)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When you use self.tr you must pass the string, not the QString variable, in your case it changes:
self.myButtons.setText(self.tr(QtCore.QString('yes')))
to
self.myButtons.setText(self.tr("yes"))
And run everything again.
I am an absolute beginner with PyQt but I have fairly conversant with Python and Pygame. I am writing a file utility for Windows and I need to get either a directory path or paths of several selected files into a variable or a list. How is this possible using pyqt? I know how to do it with tk but I have compiling errors using tk. Please try to give me a direct answer to this question instead of finding fault with my approach to this matter. My code which I tried with pyqt is given below.
import sys
from PyQt4 import QtGui
class Qtthings(QtGui.QWidget):
def __init__(self):
super(Qtthings, self).__init__()
self.initUI()
def initUI(self):
self.resize(350, 450) # screen size xy
self.center()
self.setWindowTitle('Select Directory')
self.setWindowIcon(QtGui.QIcon('dg64.ico'))
self.fileDialog = QtGui.QFileDialog(self)
self.fileDialog.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center() # get the screen center
qr.moveCenter(cp) # this where the frameshould move
self.move(qr.topLeft()) # move the top left in relation to the center
def main():
app = QtGui.QApplication(sys.argv)
ex = Qtthings()
#a = ex.fileDialog
sys.exit(app.exec_())
return
if __name__ == '__main__':
fp = main()
print fp
I found the shortest way to do this was
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
a = QtGui.QFileDialog.getOpenFileNames()
if a:
for name in a:
print name
I am using PyQt5 5.5.1 (64-bit) with Python 3.4.0 (64-bit) on Windows 8.1
64-bit.
I am having trouble restoring the position and size (geometry) of my
very simple PyQt app.
Here is minimal working application:
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class myApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
view = myApp()
sys.exit(app.exec())
What I read online is that this is the default behavior and we need to
use QSettings to save and retrieve settings from Windows registry,
which is stored in
\\HKEY_CURRENT_USER\Software\{CompanyName}\{AppName}\
Here are some of the links I read.
I could have followed those tutorials but those tutorials/docs were
written for C++ users.
C++ is not my glass of beer, and converting those codes are impossible to me.
Related:
QSettings(): How to save to current working directory
This should do.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QSettings, QPoint, QSize
class myApp(QWidget):
def __init__(self):
super(myApp, self).__init__()
self.settings = QSettings( 'My company', 'myApp')
# Initial window size/pos last saved. Use default values for first time
self.resize(self.settings.value("size", QSize(270, 225)))
self.move(self.settings.value("pos", QPoint(50, 50)))
def closeEvent(self, e):
# Write window size and position to config file
self.settings.setValue("size", self.size())
self.settings.setValue("pos", self.pos())
e.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
frame = myApp()
frame.show()
app.exec_()
I simplified this example: QSettings(): How to save to current working directory
Similar to #Valentin's response, because I feel settings are being written to registry, which will be issue for cross compatiblity. Here is the relevant startEvent() and closeEvent() for the job.
def startEvent()
self.settings = QSettings(QSettings.IniFormat,QSettings.SystemScope, '__MyBiz', '__settings')
self.settings.setFallbacksEnabled(False) # File only, not registry or or.
# setPath() to try to save to current working directory
self.settings.setPath(QSettings.IniFormat,QSettings.SystemScope, './__settings.ini')
# Initial window size/pos last saved
self.resize(self.settings.value("size", QSize(270, 225)))
self.move(self.settings.value("pos", QPoint(50, 50)))
self.tab = QWidget()
def closeEvent(self, e):
# Write window size and position to config file
self.settings.setValue("size", self.size())
self.settings.setValue("pos", self.pos())
startEvent() should be initiated at startup and closeEvent() should be taken care before quitting the main window.
You should indeed use QSetting for this.
All the Qt examples have been converted to Python. They are included in the source packages of PyQt (or PySide), which you can download here
You can also look online in the github repo, particularly in application.py of mainwindows example.
def readSettings(self):
settings = QSettings("Trolltech", "Application Example")
pos = settings.value("pos", QPoint(200, 200))
size = settings.value("size", QSize(400, 400))
self.resize(size)
self.move(pos)
def writeSettings(self):
settings = QSettings("Trolltech", "Application Example")
settings.setValue("pos", self.pos())
settings.setValue("size", self.size())
Fire writeSettings() before quitting and initiate readSettings() on startup.
In my case I use .ini files to store settings (language, default user, ...). the same code works on both Debian and Windows.
An example:
from PySide.QtCore import QSettings
self.settings = QSettings('settings.ini', QSettings.IniFormat)
...
self.settings.setValue('size', self.size())
I'm currently trying to implement some kind of file browser / "explorer" into a programme... I'm using Python and PySide in connection with the Qt-window-toolkit. More or less this youtube-video shows the behaviour I want to have at the end. However, this tutorial used C++ as programming language and I haven't been able yet to reason the right python code from the C++ example.
Basically, my problem is to get the right column (file view) showing the content of the folder clicked in the left column (tree-style folder view).
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.resize(600, 600)
self.fileBrowserWidget = QtGui.QWidget(self)
self.setCentralWidget(self.fileBrowserWidget)
self.dirmodel = QtGui.QFileSystemModel()
# Don't show files, just folders
self.dirmodel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllDirs)
self.folder_view = QtGui.QTreeView(parent=self);
self.folder_view.setModel(self.dirmodel)
self.folder_view.clicked[QtCore.QModelIndex].connect(self.clicked)
# Don't show columns for size, file type, and last modified
self.folder_view.setHeaderHidden(True)
self.folder_view.hideColumn(1)
self.folder_view.hideColumn(2)
self.folder_view.hideColumn(3)
self.selectionModel = self.folder_view.selectionModel()
self.filemodel = QtGui.QFileSystemModel()
# Don't show folders, just files
self.filemodel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
self.file_view = QtGui.QListView(parent=self);
self.file_view.setModel(self.filemodel)
splitter_filebrowser = QtGui.QSplitter()
splitter_filebrowser.addWidget(self.folder_view)
splitter_filebrowser.addWidget(self.file_view)
splitter_filebrowser.setStretchFactor(0,2)
splitter_filebrowser.setStretchFactor(1,4)
hbox = QtGui.QHBoxLayout(self.fileBrowserWidget)
hbox.addWidget(splitter_filebrowser)
def set_path(self):
self.dirmodel.setRootPath("")
def clicked(self, index):
# get selected path of folder_view
index = self.selectionModel.currentIndex()
dir_path = self.dirmodel.filePath(index)
###############################################
# Here's my problem: How do I set the dir_path
# for the file_view widget / the filemodel?
###############################################
self.filemodel.setRootPath(dir_path)
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
main.set_path()
sys.exit(app.exec_())
As you can see in my code, I've already tried to use the setRootPath-function... however, that doesn't seem to be the correct one. So I wonder, what I've got to do for getting this to work?
You need to set the root index to the appropriate one in the file model. You can do this by adding the following line to the end of the clicked() function:
self.file_view.setRootIndex(self.filemodel.index(dir_path))
I was able to figure it out from my experience using Qt in C++. The documentation for Qt in C++ is really quite good if you can figure out how it translates to Python. I was able to figure this out by looking at the QFileSystemModel documentation.
You need to set the root index of the files list view:
def clicked(self, index):
# the signal passes the index of the clicked item
dir_path = self.filemodel.filePath(index)
root_index = self.filemodel.setRootPath(dir_path)
self.file_view.setRootIndex(root_index)