how to add image with text in qlistwidget pyqt4 python? - python

How to add image/icon with text in a qlistwidget in pyqt4 python? I want to add an icon with text just like a chat system. thanks

I have tried this right now and it works, supposing you have a file named tick.png in the same folder as this script.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon
def main():
app = QtGui.QApplication(sys.argv)
window = QDialog()
list = QListWidget( window )
itm = QListWidgetItem( "Tick" );
itm.setIcon(QIcon(r"tick.png"));
list.addItem(itm);
window.show( )
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The chat-like-icon system may be different from this, but right now I don't see a way to have a QListWidgetItem with multiple smileys and text.
You may think of smileys as a particular case of a QListWidgetItem where the text is blank and only the icon is present.
Another solution is using a read-only QTextEdit as chatboard and have the user typing its text + icon + text (etc.) in a separate editable QTextEdit. Then, when he presses the send button, append everything he typed to the read-only QTextEdit.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTextEdit, QTextDocumentFragment
def main():
app = QtGui.QApplication(sys.argv)
window = QDialog()
list = QListWidget( window )
textEditor = QTextEdit( window );
textEditor.setReadOnly( True )
tick_icon = QTextDocumentFragment.fromHtml(r"<img src='tick.png'>");
textEditor.insertPlainText ( " ValiumKnight writes: " )
textEditor.textCursor().insertFragment(tick_icon);
textEditor.insertPlainText ( " Hello World " )
textEditor.textCursor().insertFragment(tick_icon);
textEditor.textCursor().insertFragment(tick_icon);
textEditor.textCursor().insertFragment(tick_icon);
window.show( )
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Bye!

Related

PyQt5 QFileDialog - Highlight Suggested File in the QListView Widget

I’m using PyQt5 on a Windows platform. I want to present a QFileDialog to the user with the suggested file highlighted in both the QListView and the QLineEdit widgets within the QFileDialog window. The selectFile() method adds the filename to the QLineEdit widget and highlightss it, but does not highlight the file in the QListView widget.
I tried the suggestion in How to setFocus() on QListView in QFileDialog in PyQt5?, but I could not see that the QListView had focus and could not highlight a file with selectFile().
In QFileDialog, is there a way to highlight the filename in the QistView and in the QLineEdit widgets? If not, is there a way to highlight the filename in just the QListView?
Here is a minimalized script that shows the filename highlighted in the QLineEdit widget.
import sys
from PyQt5.QtWidgets import QApplication, QFileDialog
from PyQt5.QtCore import QDir
class MyClass(QFileDialog):
def __init__(self):
super().__init__()
self.DontUseNativeDialog
self.openFile()
def openFile(self):
qdir = QDir()
qdir.setPath('C:\\Users\\Slalo\\Documents\\VideoGates\\PVRTop\\Folder')
qdir.setSorting(QDir.Name | QDir.Reversed)
qdirlist = qdir.entryList()
self.setWindowTitle('Open File')
self.setDirectory(qdir)
self.setNameFilter('All(*.*)')
self.selectFile(qdirlist[1])
if self.exec():
fname = self.selectedFiles()
print(fname)
if __name__ == '__main__':
app = QApplication(sys.argv)
dlg = MyClass()
sys.exit(app.exec())
After testing #musicamante 's patience, here is the solution. The QFileDialog window looks a little different than the native Windows dialog, but that's OK - it works as intended. Here is the corrected script.
import sys, os
from PyQt5.QtWidgets import QApplication, QFileDialog
class MyClass(QFileDialog):
def __init__(self):
super().__init__()
self.setOption(QFileDialog.DontUseNativeDialog)
self.openFile()
def openFile(self):
dirname = 'C:\\Users\\Slalo\\Documents\\VideoGates\\PVRTop\\Folder'
fileList = os.listdir(dirname)
self.setWindowTitle('Open File')
self.setDirectory(dirname)
self.setNameFilter('All(*.*)')
self.selectFile(fileList[1])
if self.exec():
fname = self.selectedFiles()
print(fname)
if __name__ == '__main__':
app = QApplication(sys.argv)
dlg = MyClass()
sys.exit(app.exec())

To turn back from 2nd window to 1st window (different files)

An application is being created with a large number of different windows.
The bottom line is that I am trying to get from the main window (by clicking button) to the client window. There is "Back" button in the clients window, which should return the user to the main window.
Both codes are in different files. The problem occurs at the stage of pressing the "Customers" button (Process finished with exit code -1073740791 (0xC0000409)).
Moreover, if everything is in one file, then everything works fine. But only here the program is not planned to be small, so I don't want to put a huge code in one file.
Welcome_Screen.py
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QDialog, QApplication
import Customers
class WelcomeScreen(QDialog):
def __init__(self):
super(WelcomeScreen, self).__init__()
loadUi('screens/welcomescreen.ui', self)
self.CustomerData.clicked.connect(self.go_to_CustomerData)
def go_to_CustomerData(self):
client = Customers.CustomerScreen()
widget.addWidget(client)
widget.setCurrentIndex(widget.currentIndex() + 1)
# main
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('Icons/MainIcon.png'))
app.setApplicationDisplayName('Bonus Program')
welcome = WelcomeScreen()
widget = QtWidgets.QStackedWidget()
widget.addWidget(welcome)
widget.setFixedWidth(600)
widget.setFixedHeight(475)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
Customers.py
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QMessageBox, QTableWidget, QTableWidgetItem, QTableView
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery
from PyQt5.QtGui import QIcon
import Welcome_Screen as ws
import sqlite3
db_path = 'Bonus_db.sqlite'
class CustomerScreen(QDialog):
def __init__(self):
super(CustomerScreen, self).__init__()
loadUi("screens/customerscreen.ui", self)
self.back_btn.setIcon(QIcon('Icons/Back.png'))
self.back_btn.setIconSize(QtCore.QSize(45, 60))
self.back_btn.clicked.connect(self.go_Back_to_WelcomeScreen)
# self.SoldTos.clicked.connect(self.gotoSoldTos)
def go_Back_to_WelcomeScreen(self):
welcome = ws.WelcomeScreen()
ws.widget.addWidget(welcome)
ws.widget.setCurrentIndex(ws.widget.currentIndex() + 1)
Customer_app = QApplication(sys.argv)
cust_window = CustomerScreen()
cust_window.show()
sys.exit(Customer_app.exec_())

How to make a PyQt application that only pops up a menu immediately?

I would like my application to consist only of a pop-up menu that opens immediately as soon as it is run. I attempted this solution but nothing appears when I run it:
#!/usr/bin/env python3
from PyQt5.QtCore import (Qt, QPoint)
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import (QApplication, QMenu, QAction)
def clicked():
print("CLICKED")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
menu = QMenu()
menu.addAction(QAction("&Click me", triggered=clicked))
menu.exec_(QCursor().pos())
sys.exit(app.exec_())
This will display a simple popup window with a single option, that calls the clicked function on click:
from PySide2.QtGui import QCursor
from PySide2.QtWidgets import QApplication, QMenu
def clicked():
print("CLICKED")
if __name__ == '__main__':
app = QApplication()
menu = QMenu()
menu.addAction("Click me", clicked)
menu.exec_(QCursor().pos())
Or if you want to use QAction still, then move its definition outside:
from PySide2.QtGui import QCursor
from PySide2.QtWidgets import QApplication, QMenu, QAction
def clicked():
print("CLICKED")
if __name__ == '__main__':
app = QApplication()
menu = QMenu()
action = QAction("&Click me", triggered=clicked)
menu.addAction(action)
menu.exec_(QCursor().pos())
As pointed out by ekhumoro in the comment below:
Qt does not take ownership of actions added via addAction. You must
keep an explicit reference to them, otherwise they will get
garbage-collected.
Note I am using PySide2, but it shouldn't change anything.
Okay I am not certain how minimalistic you want this Menu to be but this is a more static menu (aka it sticks around) with more than one option in case you are trying to build some kind of Menu driven Windowing platform or just a Menu of commands. Also it being a class allows it to be importable to whatever you might be developing large scale. Further you can expand the menu by adding additional menu items with different actions and lastly it follows basic pyqt programming methodologies
from sys import exit as sysExit
from PyQt5.QtWidgets import QApplication, QAction, QWidget, QHBoxLayout, QMenuBar
class MainMenu(QWidget):
def __init__(self):
QWidget.__init__(self)
self.setMaximumSize(self.minimumSize())
self.Click1Act = QAction("&Click Me 1", triggered=self.Clicked1)
self.Click2Act = QAction("&Click Me 2", triggered=self.Clicked2)
self.SimpleMenu = QMenuBar()
self.ClickMenu = self.SimpleMenu.addMenu('Clickables')
self.ClickMenu.addAction(self.Click1Act)
self.ClickMenu.addSeparator()
self.ClickMenu.addAction(self.Click2Act)
HBox = QHBoxLayout()
HBox.addWidget(self.SimpleMenu)
self.setLayout(HBox)
def Clicked1(self):
print("CLICKED ONE")
def Clicked2(self):
print("CLICKED TWO")
if __name__ == "__main__":
MainThred = QApplication([])
MainGui = MainMenu()
MainGui.show()
sysExit(MainThred.exec_())

why icon of QSystemTrayIcon not hide in my system?

I wrote a program that create a tray. I want to hide it with below code,but it not work(tray icon is visible). how solve this problem?
from PyQt5 import QtGui, QtWidgets
if __name__ == '__main__':
app = QtWidgets.QApplication([])
sysTray =QtWidgets.QSystemTrayIcon()
sysTray.setIcon(QtGui.QIcon('1.jpg'))
sysTray.hide()
app.exec_()
Just add sysTray.show() before sysTray.hide()
Try it:
import sys
from PyQt5.QtWidgets import QApplication, QMenu, QSystemTrayIcon, qApp, QMessageBox
from PyQt5.QtGui import QIcon
def run_something():
print("Running something...")
if __name__ == '__main__':
app = QApplication(sys.argv)
# Creating menu
menu = QMenu()
checkAction = menu.addAction("Check Now")
checkAction.triggered.connect(run_something)
quitAction = menu.addAction("Quit")
quitAction.triggered.connect(qApp.quit)
# Creating icon
icon = QIcon.fromTheme("system-help", QIcon('avatar.jpg')) # '1.jpg'
# Creating tray
trayIcon = QSystemTrayIcon(icon, app)
trayIcon.setContextMenu(menu)
# Showing tray
trayIcon.show()
trayIcon.setToolTip("unko!")
trayIcon.showMessage("hoge", "moge")
sys.exit(app.exec_())

Get the selected text content from other programs

When I am using other programs (e.g. opening a pdf or word), I will select some text contents (like a word or paragraph) by using the mouse. I want my python program to get this text content. How to do this using PyQt, or some other Python library?
This is an easy task, you haven't specified the pyqt version, so I'll post the solution for PyQt4, here you go:
from PyQt4.QtCore import QObject, pyqtSlot, SIGNAL, SLOT
from PyQt4.QtGui import QApplication, QMessageBox
import sys
class MyClipboard(QObject):
#pyqtSlot()
def changedSlot(self):
if(QApplication.clipboard().mimeData().hasText()):
QMessageBox.information(None, "Text has been copied somewhere!",
QApplication.clipboard().text())
def main():
app = QApplication(sys.argv)
listener = MyClipboard()
app.setQuitOnLastWindowClosed(False)
QObject.connect(QApplication.clipboard(), SIGNAL(
"dataChanged()"), listener, SLOT("changedSlot()"))
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Categories

Resources