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
Related
I'm trying to add a background using the answers from previous questions.
Sadly they don't work and return errors, either stylesheet, or the = sign, or the """.
I think it may be my location of the image? Is there something special required to store the image perhaps or something else I'm missing?
I've shown an edited down version of the code.
Thanks
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QMainWindow, QPushButton, QAction
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import pyqtSlot
import os
os.chdir(r'C:\Users\Paul Hannell\python_files')
class App(QMainWindow): # Opening Window
def __init__(self):
super().__init__()
self.title = "Timelord Timer PyQt5"
self.left = 70
self.top = 100
self.width = 1170
self.height = 740
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.setWindowIcon(QIcon(r'C:\Users\Paul Hannell\python_files\Timelord.ico'))
self.statusBar().showMessage('Message in Status Bar')
label=QLabel(self)
############################
# Background Image
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
lay = QHBoxLayout(self.centralwidget)
stylesheet = '''
MainWindow {
background-image: url(r'C:\Users\Paul Hannell\python_files\Running_Around4.png');
background-repeat: no-repeat;
background-position: center;
}
'''
#####################################
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('File')
settingsMenu = mainMenu.addMenu('Settings')
resultsMenu = mainMenu.addMenu('Results')
reportsMenu = mainMenu.addMenu('Reports')
infoMenu = mainMenu.addMenu('Info')
newButton=QAction('New', self)
newButton.setStatusTip('New Race')
#newButton.triggered.connect(self.create) #This open new event options
fileMenu.addAction(newButton)
openButton = QAction('Open' , self)
openButton.setStatusTip('Open File')
#openButton.triggered.connect(self.open) # This will open existing
fileMenu.addAction(openButton)
deleteButton=QAction('Delete', self)
deleteButton.setStatusTip('Delete Race')
#deleteButton.triggered.connect(self.create) #This delete existing event.
fileMenu.addAction(deleteButton)
exitButton=QAction('Exit', self)
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(self.close)
fileMenu.addAction(exitButton)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Your code is badly indented (and too long) so it's hard to tell, but I see several issues:
it shoud be #MainWindow in the style sheet (you're missing a #)
you need to name the App with this name: self.setObjectName('MainWindow')
you need to use setStyleSheet at some point
the url needs fixing: no quotes nor 'r'; simply the file name (maybe the space in the file name needs escaping, you could try to play with it)
This, for instance, works:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QMainWindow, QPushButton, QAction
class App(QMainWindow): # Opening Window
def __init__(self):
super().__init__()
self.setWindowTitle('hello bg')
self.setObjectName('MainWindow')
stylesheet = '''
#MainWindow {
background-image: url(/home/me/photos/DSC_0001.jpg);
background-repeat: no-repeat;
background-position: center;
}
'''
self.setStyleSheet(stylesheet)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
I'm trying to get a background image to my mainwindow but i can't get it to work properly.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QIcon
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSvg import *
from PyQt5.QtWidgets import *
from abc import abstractmethod
class App(QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.title = 'Title'
self.left = 500
self.top = 500
self.width = 440
self.height = 280
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# ...
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
#view = TableScene(ex)
ex.show()
sys.exit(app.exec_())
I've tried different kinds of methods but none of them works as it should.
I found the following code as a solution from another topic but it just gives me a black background and the rest of the widgets get laggy.
oImage = QImage("table.png")
sImage = oImage.scaled(QSize(440, 280))
palette = QPalette()
palette.setBrush(QPalette.Window, QBrush(sImage))
self.setPalette(palette)
I don't know if the whole window gets laggy or what really happens but the picture below is a screenshot of a part of the window using the code above, and as you can see it gets all black and the slider shows all the previous position it has been on, sort of laggy anyways.
I've also tried the setStyleSheet but I don't know if it's my syntax that's wrong or if it's a faulty way of doing it. Does anyone know a way of doing it correctly?
EDIT
This is my current window:
This is the picture I'm trying to implement as a background to my current window, the picture called "table.png" :
This is a visualization of what I'm trying to do, and this is made in paint since I don't know how to do it correctly:
And this is what I get if i use the code from the other topic:
One of the possible reasons why a black background appears is that QImage is null. And a QImage is null because the image is invalid or because the image path is incorrect. In this case I think it is the second case since the OP uses a relative path that is prone to errors. The solution is to build the absolute path using the script information such as its location:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
oImage = QtGui.QImage(os.path.join(CURRENT_DIR, "table.png"))
sImage = oImage.scaled(QtCore.QSize(440, 280))
palette = QtGui.QPalette()
palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(sImage))
self.setPalette(palette)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
Note: The image provided by the OP has extension .jpg but the one indicated by code is .png, maybe "imgur" has changed the extension.
Note: If the window is resized manually, the following behavior will be observed:
So for this there are 2 possible solutions depending on the developer's criteria:
Set a fixed size: self.setFixedSize(440, 280)
Adapt the image to the size of the window:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
self.oImage = QtGui.QImage(os.path.join(CURRENT_DIR, "table.png"))
# or QPixmap
# self.oPixmap = QtGui.QPixmap(os.path.join(CURRENT_DIR, "table.png"))
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawImage(self.rect(), self.oImage)
# or QPixmap
# painter.drawPixmap(self.rect(), self.oPixmap)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
or
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
self.setStyleSheet(
"""
QMainWindow{
border-image: url(%s) 0 0 0 0 stretch stretch
}
"""
% os.path.join(CURRENT_DIR, "table.png")
)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
I am using PyQt5 to create an application. The application has a MainWindow with several widgets. One of the widgets is a QLabel object that displays a video. I want to track the cursor and display the cursor coordinates as I mouse over the video when I check a radio button.
I created a MouseTracking class that I’m passing the QLabel object into as window. I have verified that the passed into the class by printing its geometry. But I’m somehow not associating the mouse tracking to window. Here is the code for the MouseTracking class. What am I doing wrong?
class MouseTracker(QLabel):
def __init__(self, window):
super().__init__(window)
self.window = window
self.window.setMouseTracking(True)
self.initUI()
def initUI(self):
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet('background-color: white; border: 1px solid black')
self.show()
def mouseMoveEvent(self, event):
x = event.x()
y = event.y()
print("X, Y = ", x, y)
self.label.setGeometry(x+30, y-15, 90, 40)
self.label.setText('(%d, %d)' % (x, y))
In your code you have enabled the mouseTracking property of the "window" but you are monitoring the mouseMoveEvent method of the MouseTracker which is incorrect. If you want to track the events of a widget without overriding any method then you must use an event filter.
In the following example I try to implement your application based on your description, for example the green QLabel represents the QLabel that the video shows. Considering the above, the solution is as follows:
from PyQt5 import QtCore, QtGui, QtWidgets
class MouseTracker(QtCore.QObject):
positionChanged = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, widget):
super().__init__(widget)
self._widget = widget
self.widget.setMouseTracking(True)
self.widget.installEventFilter(self)
#property
def widget(self):
return self._widget
def eventFilter(self, o, e):
if o is self.widget and e.type() == QtCore.QEvent.MouseMove:
self.positionChanged.emit(e.pos())
return super().eventFilter(o, e)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
self.video_label = QtWidgets.QLabel()
self.video_label.setStyleSheet("background-color: green; border: 1px solid black")
tracker = MouseTracker(self.video_label)
tracker.positionChanged.connect(self.on_positionChanged)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.video_label)
lay.addWidget(QtWidgets.QLabel())
self.resize(640, 480)
self.label_position = QtWidgets.QLabel(
self.video_label, alignment=QtCore.Qt.AlignCenter
)
self.label_position.setStyleSheet('background-color: white; border: 1px solid black')
#QtCore.pyqtSlot(QtCore.QPoint)
def on_positionChanged(self, pos):
delta = QtCore.QPoint(30, -15)
self.label_position.show()
self.label_position.move(pos + delta)
self.label_position.setText("(%d, %d)" % (pos.x(), pos.y()))
self.label_position.adjustSize()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I am trying to create a pop-up window that gets popped-up from pressing on a QPushButton. However, I have a separate QPushButton class that I would like to use. I can't seem to get it working. Anything I am doing wrong?
#import ... statements
import sys
# from ... import ... statements
from PyQt5.QtWidgets import (QMainWindow, QApplication, QPushButton, QGridLayout, QWidget, QHBoxLayout, QLabel,
QVBoxLayout)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QFontDatabase, QColor, QPalette, QMovie
from skimage import transform, io
# Create main window of the widget
class MainWindow(QWidget):
def __init__(self):
super().__init__()
#Set a title inside the widget
self.titleLabel = QLabel()
titleText = "some title text"
self.titleLabel.setText(titleText)
# Give the label some flair
self.titleLabel.setFixedWidth(1000)
self.titleLabel.setAlignment(Qt.AlignCenter)
QFontDatabase.addApplicationFont(link_to_custom_font)
font = QFont()
font.setFamily("custom_font_name")
font.setPixelSize(50)
self.titleLabel.setFont(font)
# Set first button - The "Yes" Button
self.btn1 = myButtonOne("Yes")
#Initialize GUI
self.layoutGUI()
self.initUI()
def initUI(self):
self.fromleft = 200
self.fromtop = 100
self.w = 1000
self.h = 500
self.setGeometry(self.fromleft, self.fromtop, self.w, self.h)
def layoutGUI(self):
hbox = QHBoxLayout()
hbox.setSpacing(20)
hbox.addWidget(self.btn1)
vbox = QVBoxLayout()
vbox.addWidget(self.titleLabel)
vbox.addLayout(hbox)
self.setLayout(vbox)
class myButtonOne(QPushButton):
def __init__(self, parent=None):
super(myButtonOne, self).__init__(parent)
# Set maximum border size
imSize = io.imread(imagePath)
imHeight = imSize.shape[1]
imWidth = imSize.shape[0]
# Set first button - The "Yes" Button
yesImage = someImagePath
self.setStyleSheet("background-image: url(" + yesImage + ");"
"background-repeat: none;"
"background-position: center;"
"border: none")
self.setFixedSize(imWidth, imHeight)
self.clicked.connect(self.buttonOnePushed)
def buttonOnePushed(self):
textView().show()
def enterEvent(self, event):
newImage = someOtherImagePath
self.setStyleSheet("background-image: url("+newImage+");"
"background-repeat: none;"
"background-position: center;"
"border: none")
def leaveEvent(self, event):
newImage = someImagePath
self.setStyleSheet("background-image: url("+newImage+");"
"background-repeat: none;"
"background-position: center;"
"border: none")
class textView(QWidget):
def __init(self):
textView.__init__()
theText = QLabel()
#define sizes
self.height = 550
self.width = 250
# Open QWidget
self.initUI()
# Set the text for the QLabel
someText = "Some Text for the label"
theText.setText(someText)
def initUI(self):
self.show()
# Start GUI
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
So, I am trying to keep the QPushButton classes separate, so that I can customize them. I would like to keep it like that, especially to keep it clean and readable.
First off - please read: How to create a Minimal, Complete, and Verifiable example. I had a lot of work minimizing your code, which wasted a good amount of my time.
Nonetheless, here is a minimal working code, with your own button class:
import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QLabel, QVBoxLayout
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.titleLabel = QLabel( "some label text" )
self.btn1 = myButtonOne( "button text" )
hbox = QVBoxLayout() # one vertical box seemed enough
hbox.addWidget( self.titleLabel )
hbox.addWidget( self.btn1 )
self.setLayout( hbox )
class myButtonOne(QPushButton):
def __init__(self, text, parent=None):
super(myButtonOne, self).__init__(text, parent)
self.clicked.connect(self.buttonOnePushed)
# add your customizations here
def buttonOnePushed (self) :
self.t = textView()
self.t.show()
class textView(QWidget):
def __init__(self):
super(textView, self).__init__()
self.theText = QLabel('test', self )
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
What have you done wrong in your code?
using textView().show() creates a local version of you textView-class and show()'s it:
def buttonOnePushed(self):
textView().show()
But, show() means that the code continues, where the end of your code comes, which results in cleaning up the locals. End - it's just shown for a microsecond.
def buttonOnePushed (self) :
self.t = textView()
self.t.show()
The code above stores the var as instance-attribute of the button, which is not cleaned up.
Furthermore you misspelled the init in your textView-class:
"__init" should be __init__ - else it is not called when using the constructor:
class textView(QWidget):
def __init(self):
textView.__init__()
Finally, you wanted to called show() twice:
in your textView-init you call initUI() which is calling show()
you calling show manually with textView().show()
Hope this helps! I did not include your personal style adjustments for readability.
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_())