How to make QLineEdit-QCompleter upperlines automatically - python

I have a list of texts, if the user search for a text in QLineEdit, I print the text. There is a QCompleter in QLineEdit.
The problem is, as we know Text and text are not same, but it's same to the user. So If user starts typing Text or text, I want to change it to the TEXT real time in QLineEdit. So whenever the user types a letter, I want to make it uppercase in QCompleter-QLineEdit. How can I do this? I have this atm;
from PyQt5.QtWidgets import QApplication,QPushButton,QMainWindow,QLabel,QLineEdit,QCompleter
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import QPoint
import sys
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.mwidget = QMainWindow(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
#size
self.setFixedSize(600,400)
#LINE EDIT QCOMPLETER
self.label = QLineEdit(self)
self.label.setGeometry(100,100,300,30)
self.label.setStyleSheet("color: red;"
"font: bold 15pt 'Arial';")
self.t = ["Hello","hi","Hey"]
self.label.setCompleter(QCompleter(self.t, self))
#BUTTON
self.buton = QPushButton(self)
self.buton.setText("Click")
self.buton.setGeometry(200,140,90,50)
self.buton.clicked.connect(self.hangiButon)
#SET LABEL
self.set_label = QLabel(self)
self.set_label.setGeometry(100,300,900,100)
self.set_label.setStyleSheet("color: green;"
"font: bold 18pt 'Times New Roman';")
self.show()
def hangiButon(self):
print(self.label.text(), self.t.index(self.label.text())+1)
self.set_label.setText("Pressed to --> {}.".format(self.label.text().rstrip()))
def mousePressEvent(self, event):
self.oldPos = event.globalPos()
def mouseMoveEvent(self, event):
delta = QPoint (event.globalPos() - self.oldPos)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.oldPos = event.globalPos()
app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden()
sys.exit(app.exec_())
So if I press h I want to see all of the words, not only hi and I want to change that h immediately. But couldn't figure out how.

The QCompleter widget has a setCaseSensitivity property that takes a QtCore.Qt.CaseSensitive / QtCore.Qt.CaseInsensitive or simply a 1 or 0 (docs).
The Qt documentaion says that "The default is Qt::CaseSensitive."
Changing the property to case-insensitive matching:
self.t = ["Hello","hi","Hey"]
my_completer = QCompleter(self.t, self)
my_completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
# my_completer.setCaseSensitivity(0)
self.label.setCompleter(my_completer)
To change the user input to uppercase you could add a method that changes the text:
def to_upper(self, txt):
self.label.setText(txt.upper())
which can then be connected to events such as self.label.textChanged:
self.label.textChanged.connect(self.to_upper)
Putting it together:
from PyQt5.QtWidgets import QApplication,QPushButton,QMainWindow,QLabel,QLineEdit,QCompleter
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import QPoint
import sys
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.mwidget = QMainWindow(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
#size
self.setFixedSize(600,400)
#LINE EDIT QCOMPLETER
self.label = QLineEdit(self)
self.label.setGeometry(100,100,300,30)
self.label.setStyleSheet("color: red;"
"font: bold 15pt 'Arial';")
self.label.textChanged.connect(self.to_upper)
self.t = ["Hello","hi","Hey"]
my_completer = QCompleter(self.t, self)
#my_completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
my_completer.setCaseSensitivity(0)
self.label.setCompleter(my_completer)
#BUTTON
self.buton = QPushButton(self)
self.buton.setText("Click")
self.buton.setGeometry(200,140,90,50)
self.buton.clicked.connect(self.hangiButon)
#SET LABEL
self.set_label = QLabel(self)
self.set_label.setGeometry(100,300,900,100)
self.set_label.setStyleSheet("color: green;"
"font: bold 18pt 'Times New Roman';")
self.show()
def to_upper(self, txt):
self.label.setText(txt.upper())
def hangiButon(self):
print(self.label.text(), self.t.index(self.label.text())+1)
self.set_label.setText("Pressed to --> {}.".format(self.label.text().rstrip()))
def mousePressEvent(self, event):
self.oldPos = event.globalPos()
def mouseMoveEvent(self, event):
delta = QPoint (event.globalPos() - self.oldPos)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.oldPos = event.globalPos()
app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden()
sys.exit(app.exec_())

Related

KeyPressEvent() doesn't work with label when I add PushButtons

`
from PyQt5.QtCore import Qt
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QLabel, QPushButton
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 1000, 1000)
self.setWindowTitle('Example')
self.label_backround = QLabel(self)
self.label_backround.move(100, 100)
self.label_backround.resize(800, 800)
self.label = QLabel(self)
self.label.setText("xxxxx")
self.label.move(340, 340)
self.Button1 = QPushButton('1', self)
self.Button1.move(580, 250)
self.Button2 = QPushButton('2', self)
self.Button2.move(590, 560)
self.Button3 = QPushButton('3', self)
self.Button3.move(210, 660)
def keyPressEvent(self, event):
x = self.label.x()
y = self.label.y()
if event.key() == Qt.Key_Left:
self.label.move(x - 15, y)
elif event.key() == Qt.Key_Up:
self.label.move(x, y - 15)
elif event.key() == Qt.Key_Right:
self.label.move(x + 15, y)
elif event.key() == Qt.Key_Down:
self.label.move(x, y + 15)
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
`I have a window on which is a label that should move when I press the up, down, right and left buttons on keyboard. It works, but when I add some PushButtons the label doesn't move.
Сan anyone know what this is about?
The widget that receives the keypress event only the widget that has the focus, and by default many widgets like the QPushButtons take the focus unlike a QWidget. In this case you should not use keyPressEvent but a QShorcut that allows you to capture keyboard events independently of the widgets (obviously you can set limitations through context). Considering the above, the solution is:
import sys
from PyQt5.QtCore import QPoint, Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QShortcut
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 1000, 1000)
self.setWindowTitle("Example")
self.label_backround = QLabel(self)
self.label_backround.move(100, 100)
self.label_backround.resize(800, 800)
self.label = QLabel(self)
self.label.setText("xxxxx")
self.label.move(340, 340)
self.Button1 = QPushButton("1", self)
self.Button1.move(580, 250)
self.Button2 = QPushButton("2", self)
self.Button2.move(590, 560)
self.Button3 = QPushButton("3", self)
self.Button3.move(210, 660)
QShortcut(QKeySequence(Qt.Key_Left), self, activated=self.move_left)
QShortcut(QKeySequence(Qt.Key_Up), self, activated=self.move_up)
QShortcut(QKeySequence(Qt.Key_Right), self, activated=self.move_right)
QShortcut(QKeySequence(Qt.Key_Down), self, activated=self.move_down)
def move_left(self):
self.label.move(self.label.pos() + QPoint(-15, 0))
def move_up(self):
self.label.move(self.label.pos() + QPoint(0, -15))
def move_right(self):
self.label.move(self.label.pos() + QPoint(15, 0))
def move_down(self):
self.label.move(self.label.pos() + QPoint(0, 15))
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

PySide/PyQt Overlay widget

I am trying to achieve something like this in PySide: https://codepen.io/imprakash/pen/GgNMXO
What I want to do is create a child window frameless with a black overlay below.
I didn't succeed to create a child window frameless and the overlay...
This is a base code to replicate the HTML:
from PySide import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
popup = QtGui.QDialog(self)
popup.setWindowFlags(QtCore.Qt.FramelessWindowHint)
popup.setLayout(QtGui.QHBoxLayout())
popup.layout().addWidget(QtGui.QLabel("HI"))
popup.show()
print "clicked"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
If you comment the line with the FramelessWindowHint, the window comes, else nothing happen...
I really hope that someone could help me. Thank you for the time you spent to read my question.
I'll be using PyQt5 for this explanation. It might have some differences to PySide (which I'm not sure if its still maintained) and PyQt4, but it shouldn't be too hard to convert.
The following example has a parent widget which a few buttons. One of them (the obvious one) calls for the popup. I've prepared the example to deal with the parent resize but have not made any code regarding mouse events of dragging the popup (see mouseMoveEvent and mouseReleaseEvent for that).
So here is the code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class TranslucentWidgetSignals(QtCore.QObject):
# SIGNALS
CLOSE = QtCore.pyqtSignal()
class TranslucentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TranslucentWidget, self).__init__(parent)
# make the window frameless
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.fillColor = QtGui.QColor(30, 30, 30, 120)
self.penColor = QtGui.QColor("#333333")
self.popup_fillColor = QtGui.QColor(240, 240, 240, 255)
self.popup_penColor = QtGui.QColor(200, 200, 200, 255)
self.close_btn = QtWidgets.QPushButton(self)
self.close_btn.setText("x")
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
self.close_btn.setFont(font)
self.close_btn.setStyleSheet("background-color: rgb(0, 0, 0, 0)")
self.close_btn.setFixedSize(30, 30)
self.close_btn.clicked.connect(self._onclose)
self.SIGNALS = TranslucentWidgetSignals()
def resizeEvent(self, event):
s = self.size()
popup_width = 300
popup_height = 120
ow = int(s.width() / 2 - popup_width / 2)
oh = int(s.height() / 2 - popup_height / 2)
self.close_btn.move(ow + 265, oh + 5)
def paintEvent(self, event):
# This method is, in practice, drawing the contents of
# your window.
# get current window size
s = self.size()
qp = QtGui.QPainter()
qp.begin(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
qp.setPen(self.penColor)
qp.setBrush(self.fillColor)
qp.drawRect(0, 0, s.width(), s.height())
# drawpopup
qp.setPen(self.popup_penColor)
qp.setBrush(self.popup_fillColor)
popup_width = 300
popup_height = 120
ow = int(s.width()/2-popup_width/2)
oh = int(s.height()/2-popup_height/2)
qp.drawRoundedRect(ow, oh, popup_width, popup_height, 5, 5)
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
qp.setFont(font)
qp.setPen(QtGui.QColor(70, 70, 70))
tolw, tolh = 80, -5
qp.drawText(ow + int(popup_width/2) - tolw, oh + int(popup_height/2) - tolh, "Yep, I'm a pop up.")
qp.end()
def _onclose(self):
print("Close")
self.SIGNALS.CLOSE.emit()
class ParentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ParentWidget, self).__init__(parent)
self._popup = QtWidgets.QPushButton("Gimme Popup!!!")
self._popup.setFixedSize(150, 40)
self._popup.clicked.connect(self._onpopup)
self._other1 = QtWidgets.QPushButton("A button")
self._other2 = QtWidgets.QPushButton("A button")
self._other3 = QtWidgets.QPushButton("A button")
self._other4 = QtWidgets.QPushButton("A button")
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self._popup)
hbox.addWidget(self._other1)
hbox.addWidget(self._other2)
hbox.addWidget(self._other3)
hbox.addWidget(self._other4)
self.setLayout(hbox)
self._popframe = None
self._popflag = False
def resizeEvent(self, event):
if self._popflag:
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
def _onpopup(self):
self._popframe = TranslucentWidget(self)
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
self._popframe.SIGNALS.CLOSE.connect(self._closepopup)
self._popflag = True
self._popframe.show()
def _closepopup(self):
self._popframe.close()
self._popflag = False
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
main = ParentWidget()
main.resize(500, 500)
main.show()
sys.exit(app.exec_())
Which results in the following:
The logic is the following. You create an empty Widget and manually draw the background and popup (paintEvent). You add a button for closing the popup. For this you build a Signal and let the parent widget do the closing. This is important because you need to make the parent widget control some important elements of the popup (such as closing, resizng, etc.). You can add far more complexity but hopefully the example will suffice for starters.
Thanks to armatita, I succeed to get what I wanted. For now, there are some issues but it works and I get the result that I wanted.
I give you the code to the next who will be looking for the same thing.
from PySide import QtCore, QtGui
import sys
class CtmWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.button = QtGui.QPushButton("Close Overlay")
self.setLayout(QtGui.QHBoxLayout())
self.layout().addWidget(self.button)
self.button.clicked.connect(self.hideOverlay)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
path = QtGui.QPainterPath()
path.addRoundedRect(QtCore.QRectF(self.rect()), 10, 10)
mask = QtGui.QRegion(path.toFillPolygon().toPolygon())
pen = QtGui.QPen(QtCore.Qt.white, 1)
painter.setPen(pen)
painter.fillPath(path, QtCore.Qt.white)
painter.drawPath(path)
painter.end()
def hideOverlay(self):
self.parent().hide()
class Overlay(QtGui.QWidget):
def __init__(self, parent, widget):
QtGui.QWidget.__init__(self, parent)
palette = QtGui.QPalette(self.palette())
palette.setColor(palette.Background, QtCore.Qt.transparent)
self.setPalette(palette)
self.widget = widget
self.widget.setParent(self)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor(0, 0, 0, 127)))
painter.end()
def resizeEvent(self, event):
position_x = (self.frameGeometry().width()-self.widget.frameGeometry().width())/2
position_y = (self.frameGeometry().height()-self.widget.frameGeometry().height())/2
self.widget.move(position_x, position_y)
event.accept()
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
self.popup = Overlay(self, CtmWidget())
self.popup.hide()
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
self.popup.show()
print "clicked"
def resizeEvent(self, event):
self.popup.resize(event.size())
event.accept()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Once again thank you both of you(ymmx and armatita) to spend time on my issue.
did you try replacing popup.show() by popup.exec_()? and remove self as a parameter of the Qdialog? I change QDialog to QmessageBox to be able to quit the subwindow but it still work with the QDialog.
popup = QMessageBox()
popup.setWindowFlags( Qt.FramelessWindowHint)
popup.setLayout( QHBoxLayout())
popup.layout().addWidget( QLabel("HI"))
popup.exec_()
update
class Popup(QDialog ):
def __init__(self):
super().__init__()
self.setWindowFlags( Qt.CustomizeWindowHint)
self.setLayout( QHBoxLayout())
Button_close = QPushButton('close')
self.layout().addWidget( QLabel("HI"))
self.layout().addWidget( Button_close)
Button_close.clicked.connect( self.close )
self.exec_()
print("clicked")
def mousePressEvent(self, event):
self.oldPos = event.globalPos()
def mouseMoveEvent(self, event):
delta = QPoint (event.globalPos() - self.oldPos)
#print(delta)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.oldPos = event.globalPos()
class MainWindow( QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(800, 500)
self.button = QPushButton("Click Me")
self.setLayout( QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
Popup( )
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

PyQt5 set a QLabel x axis automatically center of the window

How can I set x axis of the QLabel the exact center of the window? I have this example
from PyQt5.QtWidgets import QMainWindow,QApplication,QLabel
from PyQt5 import QtCore
import sys
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.mwidget = QMainWindow(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setFixedSize(700,400)
self.label = QLabel(self)
self.label.setText("Center of the window")
self.label.setStyleSheet("color:green;"
"font: bold 20pt 'Arial'")
self.label.setGeometry(150,200,300,100)
self.show()
app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden()
sys.exit(app.exec_())
What to do on self.label.setGeometry so the label will be on the center of the window all the time? Is there a method like setCenter() ?
Use a vertical layout. The label will expand to fill the available space, and the text will be aligned centrally by default:
from PyQt5.QtWidgets import QWidget, QVBoxLayout
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setFixedSize(700,400)
self.label = QLabel(self)
self.label.setText("Center of the window")
self.label.setStyleSheet("color:green;"
"font: bold 20pt 'Arial'")
self.label.setAlignment(QtCore.Qt.AlignCenter)
widget = QWidget(self)
layout = QVBoxLayout(widget)
layout.addWidget(self.label)
self.setCentralWidget(widget)
self.show()

PyQt5 mousetracking not working

I've found an example that changing a QPushButton's icon when mouse is hover on it. I tried to convert it to my codes, but there are some problems. First check the example I found, it's really short. http://paste.ubuntu.com/17302717/
These codes changing the icon of button if mouse is on it. Here is my codes that raises error
return QPushButton.mouseMoveEvent(QPushButton, event)
TypeError: QPushButton.mouseMoveEvent(QMouseEvent): first argument of unbound method must have type 'QPushButton'
from PyQt5.QtWidgets import QApplication,QPushButton,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize
import PyQt5.QtWidgets,PyQt5.QtCore,sys
class cssden(QMainWindow):
def __init__(self):
super().__init__()
self.mwidget = QMainWindow(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setMouseTracking(True)
self.setFixedSize(1400,923)
#Button
self.mbutton = QPushButton(self)
self.mbutton.setStyleSheet("background-color: rgb(30,30,30);"
"background-image: url('resources/twitter-logo.png');"
"border: 3px solid black;"
"background-position: center;"
)
self.mbutton.setGeometry(2,300,110,60)
self.mbutton.clicked.connect(self.yaz)
self.show()
def mouseMoveEvent(self, event):
if event.pos().x()>self.mbutton.width()-10 or event.pos().y()>self.mbutton.height()-10\
or event.pos().x() < 10 or event.pos().y()< 10:
bmp = QIcon("1.png")
self.mbutton.setIcon(bmp)
else:
bmp = QIcon('2.png')
self.mbutton.setIcon(bmp)
self.mbutton.setIconSize(QSize(200,200))
return QPushButton.mouseMoveEvent(self, event)
def yaz(self):
print ("button pressed")
app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden()
sys.exit(app.exec_())
I don't understand where is the problem. I tried to change return QPushButton.mouseMoveEvent(self, event) to return QPushButton.mouseMoveEvent(QPushButton, event) and other versions, but not worked. What I'm missing, how can I fix this?
EDIT: I changed self.setMouseTracking(True) to self.mbutton.setMouseTracking(True) and no error now, but icon is not changing anyway. Why the icon is not changing?
Your code has a few problems, namely with imports. The main problem though is that you don't need this: return QPushButton.mouseMoveEvent(self, event)
Try the following corrections to your code:
from PyQt5.QtWidgets import QApplication,QPushButton,QWidget from
PyQt5.QtGui import QIcon from PyQt5.QtCore import QSize from PyQt5
import QtCore, QtWidgets, QtGui
import PyQt5.QtWidgets,PyQt5.QtCore,sys
class cssden(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# self.mwidget = QMainWindow(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setMouseTracking(True)
self.setFixedSize(1400,923)
#Button
self.mbutton = QPushButton(self)
self.mbutton.setStyleSheet("background-color: rgb(30,30,30);"
"background-image: url('resources/twitter-logo.png');"
"border: 3px solid black;"
"background-position: center;"
)
self.mbutton.setGeometry(2,300,110,60)
self.mbutton.clicked.connect(self.yaz)
self.show()
def mouseMoveEvent(self, event):
if event.pos().x()>self.mbutton.width()-10 or event.pos().y()>self.mbutton.height()-10\
or event.pos().x() < 10 or event.pos().y()< 10:
bmp = QIcon("1.png")
self.mbutton.setIcon(bmp)
else:
print(1)
bmp = QIcon('2.png')
self.mbutton.setIcon(bmp)
self.mbutton.setIconSize(QSize(200,200))
# return self.mbutton.mouseMoveEvent(event)
def yaz(self):
print ("button pressed")
app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color:
rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden() sys.exit(app.exec_())
In any case, I don't really understood what you are trying to achieve. If you need to create some kind of hover effect to your button there are other, much better ways. For example this one:
from PyQt5.QtWidgets import QApplication,QPushButton,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtWidgets, QtGui
import PyQt5.QtWidgets,PyQt5.QtCore,sys
class HoverButton(QPushButton):
mouseHover = QtCore.pyqtSignal(bool)
def __init__(self, parent=None):
QPushButton.__init__(self, parent)
self.setMouseTracking(True)
def enterEvent(self, event):
self.mouseHover.emit(True)
bmp = QIcon("1.png")
self.setIcon(bmp)
self.setIconSize(QSize(200,200))
def leaveEvent(self, event):
self.mouseHover.emit(False)
bmp = QIcon("2.png")
self.setIcon(bmp)
self.setIconSize(QSize(200,200))
class cssden(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# self.mwidget = QMainWindow(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setMouseTracking(True)
self.setFixedSize(1400, 923)
#Button
self.mbutton = HoverButton(self)
self.mbutton.setStyleSheet("background-color: rgb(30,30,30);"
"background-image: url('resources/twitter-logo.png');"
"border: 3px solid black;"
"background-position: center;"
)
self.mbutton.setGeometry(2,300,110,60)
self.mbutton.clicked.connect(self.yaz)
self.show()
def yaz(self):
print("button pressed")
app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden()
sys.exit(app.exec_())
I would advise the following answers:
PyQT how to make a QEvent.Enter on QPushbutton? (my solution is based on this method)
Pyqt Mouse hovering on a QPushButton

Adjust widths of QHBoxLayout

Here is the code:
#!/usr/bin/env python3
import sys, time
from PySide import QtCore, QtGui
import base64
# Usage: Toast('Message')
class Toast(QtGui.QDialog):
def __init__(self, title, msg, duration=2):
QtGui.QDialog.__init__(self)
self.duration = duration
self.title_label = QtGui.QLabel(title)
self.title_label.setAlignment(QtCore.Qt.AlignLeft)
self.msg_label = QtGui.QLabel(msg)
self.icon_button = QLabelButton()
img_b64 = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAITgAACE4BjDEA7AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAABJdEVYdENvcHlyaWdodABQdWJsaWMgRG9tYWluIGh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL3B1YmxpY2RvbWFpbi9Zw/7KAAAB2ElEQVRIibWVPW/TUBiFz7mJTBFSGgnUqmABRgpMUYi53pCK1IWxUxd2BgYk/goDAzuq+AFILEhIZUuq/ACPrYRKGSJPdHkPQx3UOK7tJOKd7Guf57nXH++lJFRVr9e70el03pLcBnAnH/4t6SzLsvdpml5U5duVdABhGDLLsj6AjSvD9wFshWHIujzrVgBcrqLb7b6U9AoASH6aTqdf62YPAK6WDiBN0wszO52dm9lpEzhQs4LhcNhzzj13zj2TtDUXJH+Z2bGZ/ZhMJulSApL03r+WtNdoluS38Xj8USWw0kcUx/F+UzgASNqL43i/7NqCwHu/A+CgKfxKHeTZagGAPsnWsvQ8028ieLIsvCq7IJD0eFV6WXZO4L3fzFvCSkVy23u/ea2A5KNV4dcx5gRm9nBdQZFRfAcP1hUUGXMC59zagiLjn2AwGNwCsPCjrFA7OWteEATBrqRG3bWqJLkgCHZn523gsrnFcdwi+YXkrGEJAMxMs+OSonNutukwF9DMWiQpSUyS5Kmku+vOvKzM7KxtZu8A3PwfAgB/2iQ/m9m9qrtIxgBuF4bPJY1qBD8b7clJkryQ9KYg/TAajb7XZRt9NVEUHUk6BHAC4ETSYRRFR02yfwEMBLRPQVtfqgAAAABJRU5ErkJggg=="
pixmap = QtGui.QPixmap()
pixmap.loadFromData(base64.b64decode(img_b64))
self.icon_button.setPixmap(pixmap)
self.icon_button.resize(20, 20)
self.connect(self.icon_button, QtCore.SIGNAL("clicked()"), self.close)
title_layout = QtGui.QVBoxLayout()
title_layout.addWidget(self.title_label)
title_layout.addWidget(self.msg_label)
layout = QtGui.QHBoxLayout()
layout.addWidget(self.icon_button)
layout.addLayout(title_layout)
self.setGeometry(0, 0, 200, 70)
self.setLayout(layout)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
# self.setStyleSheet("border: 1px solid red; border-radius: 5px;")
self.toastThread = ToastThread(self.duration)
self.toastThread.finished.connect(self.close)
self.toastThread.start()
class ToastThread(QtCore.QThread):
def __init__(self, n_seconds):
QtCore.QThread.__init__(self)
self.n_seconds = n_seconds
def run(self):
time.sleep(self.n_seconds)
class QLabelButton(QtGui.QLabel):
def __init(self, parent):
QLabel.__init__(self, parent)
def mouseReleaseEvent(self, ev):
self.emit(QtCore.SIGNAL('clicked()'))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
program = Toast("hi", "there", 10)
program.show()
sys.exit(app.exec_())
Apparent the image label on the left is taking too much space. How can I fix this?
A horizontal layout will give each widget an equal amount of space by default, but you can adjust the ratio like this:
layout.addWidget(self.icon_button, 1)
layout.addLayout(title_layout, 3)
So that gives the title three times as much space as the icon.
This should work, just add:
self.icon_button.setFixedWidth(30)
by default it seperates the two widgets with equal width (=100)

Categories

Resources