How can I make modern search bar in PySide2? - python-3.x

I was making my own web browser until I realized that making a searchbar was a difficult task. I tried removing the title bar, but it didn't work out as expected because of pyside2 limitations. Then, I made my own searchbar but it wasn't interactive and the design was awful. So, I was looking around to see how I can make a draggable searchbar without a titlebar with stylesheets included and I found no recourses online. Therefore, StackOverflow was my last thought on how I can resolve and ask for information about this issue. Please leave any comments if I made any mistakes, Thank you! :D
import sys
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from PySide2.QtWebEngine import *
from PySide2.QtWebEngineWidgets import *
class BrowserEngine(QWidget):
def __init__(self, *args, **kwargs):
super(BrowserEngine, self).__init__()
self.webview = QWebEngineView(self)
self.webview.load("https://www.duckduckgo.com")
self.setMinimumSize(800, 600)
self.mainLayout = QVBoxLayout()
self.mainLayout.addWidget(self.webview)
self.mainLayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.mainLayout)
class BrowserWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(BrowserWindow, self).__init__()
self.setWindowTitle("DuckDuckGo")
self.widget = BrowserEngine()
self.setCentralWidget(self.widget)
if (__name__ == '__main__'):
app = QApplication(sys.argv)
module = BrowserWindow().show()
sys.exit(app.exec_())

Use QlineEdit and setPlaceHolderText, if you want some effects to use like google search completer, use QCompleter. Hope it helps you. As far as I come across, there is nothing called as search bar option in pyqt5.

Related

How can I put the RadioBoxes over the Layout?

I designed the following window. However, when running the code, the RadioBoxes stay behind the layout that contains the frame and the string. Could someone please tell me how to avoid this?
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Window')
self.setFixedSize(550,440)
self.LaySelf = QGridLayout()
self.initWidgets()
self.initUI()
self.show()
def initWidgets(self):
self.Panel = QFrame()
self.Panel.setFrameStyle(QFrame.StyledPanel)
self.Panel.setLineWidth(2)
self.Panel.setStyleSheet('background-color:#f4f2f1')
self.Btt = QRadioButton('Radio',self)
self.Label = QLabel(' '*40+'Hi')
def initUI(self):
self.LaySelf.addWidget(self.Panel,0,0,-1,6)
self.LaySelf.addWidget(self.Label,0,0,-1,6)
self.setLayout(self.LaySelf)
self.Btt.move(200,200)
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
In order to make radio button on top of QFrame you need to add it to the Frame. Currently the Radio Buttons stay behind Frame which is covering the layout.
Replace QRadioButton('Radio',self) with QRadioButton('Radio',self.Panel)
Also here is a link to another thread which demostrates Frame Usage with multiple QWidgets

PySide2 How to unassign current layout and assign a new one to a window widget? .count() gives attribute error?

I'm new to PySide2, started using it yesterday. I'm teaching myself from the API documentation and info I find online. I'm trying to make a small app with it to teach myself. My idea for the app was using a View like model, as you go pressing on certain buttons I delete the current layout on the window and present you with an entire new one. This foments modularity as each layout wouldn't be dependent on each other but instead fully individual. (Each part of the app is broadly different and requires almost all widgets to be deleted).
However whenever I search how to delete a layout or remove all of its widgets I always encounter a piece of code like this (This is actually from a question asked 6 months ago):
def clearLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
Yet when I implement something like that, even the exact same function and then call it using, self.clearLayout(self.layout) I get the following error:
File "GUI.py", line 45, in home
self.clearLayout(self.layout)
File "GUI.py", line 16, in clearLayout
while layout.count():
AttributeError: 'builtin_function_or_method' object has no attribute 'count'
I'm assuming I probably forgot to import something important, but I can't just seem to find what. Here is a list with my imports.
import sys
from PySide2.QtWidgets import QApplication, QLabel, QLineEdit, QWidget
from PySide2.QtWidgets import QDialog, QPushButton, QVBoxLayout, QLayout
I also installed PySide2 using pip install PySide2 on command line (Anaconda). Do I have to do something else?
Thank you so much, sorry post is so long, just wanted to give you the whole information from the beginning :)
EDIT:
Further testing has led me to realise I cannot use any of the virtual functions of QLayout, or its subclasses. Apparently I have to implement them myself within the code. I believe it could be this. I don't know how to implement them though. I'm going to keep trying.
EDIT 2: Some people asked for a reporducible example so here is the code that doesn't work.
import sys
from PySide2.QtWidgets import QApplication, QLabel, QLineEdit, QWidget
from PySide2.QtWidgets import QDialog, QPushButton, QVBoxLayout, QLayout
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Program")
self.setGeometry(300, 300, 300, 300)
self.start()
def clearLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
def start(self):
self.startbutton = QPushButton("Start App")
layout = QVBoxLayout()
layout.addWidget(self.startbutton)
self.setLayout(layout)
self.startbutton.clicked.connect(self.home)
def home(self):
self.clearLayout(self.layout)
self.message=QLabel("Welcome to homepage")
layout=QVBoxLayout()
layout.addWidget(self.message)
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication([])
window=Window()
window.show()
sys.exit(app.exec_())

Why doesn't this custom QWidget display correctly

I'm retrying this question with a much better code example.
The code below, in its current form, will display a green shaded QWidget in a window, which is what I want. However, when commenting out the line:
self.widget = QWidget(self.centralwidget)
and uncommenting,
self.widget = Widget_1(self.centralwidget)
the green box doesn't display. The Widget_1 class is a simple subclass of QWidget, so I'm trying to wrap my head around where the breakdown is occurring. There are no error messages, and the print("Test") line within the Widget_1 class is outputting just fine, so I know everything is being called properly.
I'm not looking to use any type of automated layouts for reasons I don't need to go into here. Can you help me to understand why the green rectangle isn't displaying, and what correction I would need to make in order to utilize the Widget_1 class?
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import QRect
import sys
class Main_Window(object):
def setupUi(self, seating_main_window):
seating_main_window.setObjectName("seating_main_window")
seating_main_window.setEnabled(True)
seating_main_window.resize(400, 400)
self.centralwidget = QWidget(seating_main_window)
self.centralwidget.setObjectName("centralwidget")
########### The following two lines of code are causing the confusion #######
# The following line, when uncommented, creates a shaded green box in a window
self.widget = QWidget(self.centralwidget) # Working line
# The next line does NOT create the same shaded green box. Where is it breaking?
# self.widget = Widget_1(self.centralwidget) # Non-working line
self.widget.setGeometry(QRect(15, 150, 60, 75))
self.widget.setAutoFillBackground(False)
self.widget.setStyleSheet("background: rgb(170, 255, 0)")
self.widget.setObjectName("Widget1")
seating_main_window.setCentralWidget(self.centralwidget)
class Widget_1(QWidget):
def __init__(self, parent=None):
super().__init__()
self.setMinimumSize(10, 30) # I put this in thinking maybe I just couldn't see it
print("Test") # I see this output when run when Widget_1 is used above
class DemoApp(QMainWindow, Main_Window):
def __init__(self):
super().__init__()
self.setupUi(self)
if __name__ == '__main__': # if we're running file directly and not importing it
app = QApplication(sys.argv) # A new instance of QApplication
form = DemoApp() # We set the form to be our ExampleApp (design)
form.show() # Show the form
app.exec_() # run the main function
Accoriding to this Qt Wiki article:
How to Change the Background Color of QWidget
you must implement paintEvent in a custom QWidget subclass in order to use stylesheets. Also, since the widget is not part of a layout, you must give it a parent, otherwise it will not be shown. So your Widget_1 class must look like this:
from PyQt5.QtWidgets import QStyleOption, QStyle
from PyQt5.QtGui import QPainter
class Widget_1(QWidget):
def __init__(self, parent=None):
super().__init__(parent) # set the parent
print("Test")
def paintEvent(self, event):
option = QStyleOption()
option.initFrom(self)
painter = QPainter(self)
self.style().drawPrimitive(QStyle.PE_Widget, option, painter, self)
super().paintEvent(event)

Python: CheckBox-es in QTableWidget's column

I've just started to work with python, so I run into problem. I've searched everywhere, but I couldn't find similar example.
So, the problem is following: I made a simple GUI using QT-Designer. QTableWidget is being filled out by clicking on button Analyse. (as you can see on the picture)
link for picture
When I select one checkBox the rest of them are being selected randomly, and I don't know why.
As I said, I'm new at Python, so the good explanation would mean a lot to me. Here is the source code:
import sys
from PyQt4 import QtGui,QtCore
from IDCS import *
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.connect(self.ui.analyseButton, QtCore.SIGNAL('clicked()'), self.doAnalyse)
self.connect(self.ui.quitButton, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()'))
def doAnalyse(self):
self.ui.tableWidget.setRowCount(10)
chkBoxItem = QtGui.QTableWidgetItem()
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
for i in range(10):
self.ui.tableWidget.setItem(i, 0, chkBoxItem)
self.ui.tableWidget.setItem(i, 1, QtGui.QTableWidgetItem("description %s" % (i+1)))
self.ui.tableWidget.setItem(i, 2, QtGui.QTableWidgetItem("name %s" % (i+1)))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())e
You are making only one instance of the CheckBox and putting it in 10 different places and that is wrong. You have to make 10 instances of CheckBox, and you will do that by moving those 3 lines of code, in which you are creating instance of CheckBox, under the for loop below.

PyQt and QtDesigner

I am trying to implement a LED in PyQt named disLDR1 by trying to change the background color. I am trying to use QPalette to change the BackgroundRole. But what is the equivalent of Qt::red?
Is this the correct way to set the background color or is there any other way?
#!/usr/bin/python -d
import sys
from PyQt4 import QtCore, QtGui
from main import Ui_Form
from PyQt4.QtGui import QPalette
class Top(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
for i in 1, 10:
self.setOff()
self.setOn()
def setOff(self):
self.pal = QPalette(self.ui.disLDR1.palette())
self.pal.setColor(self.ui.disLDR1.backgroundRole(), <<<RED COLOR>>>)
self.ui.disLDR1.setPalette(pal)
def setOn(self):
self.pal = QPalette(self.ui.disLDR1.palette())
self.pal.setColor(self.ui.disLDR1.backgroundRole(), <<<GREEN COLOR>>>)
self.ui.disLDR1.setPalette(pal)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = Top()
myapp.show()
sys.exit(app.exec_())
EDIT: I have been trying to take help from In Qt, how do I set the background color of a widget like combobox or double spin box? but don't know what to substitute for QT::red
You can find the list of predefined Qt color objects at this link. In this case you would just need to use QtCore.Qt.red and QtCore.Qt.blue. You could also use the QColor class to generate arbitrary colors.
It's a matter of preference, but I personally think the easiest and most powerful way to go would be to use a style sheet.

Resources