PyQt Change Direction of QWidget from right to left - python

I would like to change a direction of widget From Right to left by using SetLyouatDirection but does not work
This my result :
this my code :
for item in listConcrdance:
c+=1
widgitItem = QtGui.QListWidgetItem()
widget = QtGui.QWidget()
widgetText=QtGui.QLabel(str(c)+". "+item[1]+" ("+self.process.convertNumberToNameOFSorat(item[0][1])+":"+item[0][2]+")")
widgetText.setLayoutDirection(QtCore.Qt.RightToLeft)
widgetLayout = QtGui.QHBoxLayout()
widgetLayout.addWidget(widgetText)
widgetLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
widget.setLayout(widgetLayout)
self.listWidgetQuran.addItem(widgitItem)
widgitItem.setSizeHint(widget.sizeHint())
self.listWidgetQuran.setItemWidget(widgitItem, widget)

Use [your_label].setAlignment(QtCore.Qt.AlignRight):
from PyQt4 import QtCore
from PyQt4 import QtGui
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent=parent)
self.verticalLayout = QtGui.QVBoxLayout(self)
self.listWidget = QtGui.QListWidget(self)
self.verticalLayout.addWidget(self.listWidget)
for item in range(10):
widgitItem = QtGui.QListWidgetItem(self.listWidget)
widget = QtGui.QWidget()
widgetText = QtGui.QLabel(str(item))
if item % 2 == 0:
widgetText.setAlignment(QtCore.Qt.AlignRight)
else:
widgetText.setAlignment(QtCore.Qt.AlignLeft)
widgetLayout = QtGui.QHBoxLayout()
widgetLayout.addWidget(widgetText)
widget.setLayout(widgetLayout)
widgitItem.setSizeHint(widget.sizeHint())
self.listWidget.setItemWidget(widgitItem, widget)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Output:

Related

How to align a QPushButton inside window?

I want to align a QPushButton to the bottom right corner, but without a fixed size, because if I use a fixed size and resize the window, it doen't look good anymore. Here's my code:
self.copy_btn = QtWidgets.QPushButton(self)
self.copy_btn.setText("Copy")
self.copy_btn.move(370, 350)
As you can see, I'm currenctly using .move(). I tried it with .setAlignment(QtCore.Qt.AlignRight), because it worked for the label, but it doesn't work for QPushButton.
There are several solutions depending on the context:
Using a QXBoxLayout
from PyQt5 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.copy_btn = QtWidgets.QPushButton()
self.copy_btn.setText("Copy")
lay = QtWidgets.QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.addStretch()
lay.addWidget(self.copy_btn, alignment=QtCore.Qt.AlignRight)
# or
# lay = QtWidgets.QHBoxLayout(self)
# lay.setContentsMargins(0, 0, 0, 0)
# lay.addStretch()
# lay.addWidget(self.copy_btn, alignment=QtCore.Qt.AlignBottom)
self.resize(640, 480)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Using an eventFilter
from PyQt5 import QtCore, QtWidgets
class Resizer(QtCore.QObject):
def __init__(self, widget):
super().__init__(widget)
self._widget = widget
self.widget.installEventFilter(self)
if not self.widget.isWindow():
self.widget.window().installEventFilter(self)
#property
def widget(self):
return self._widget
def eventFilter(self, obj, event):
if obj is self.widget and not self.widget.isWindow():
if event.type() == QtCore.QEvent.ParentAboutToChange:
self.widget.window().removeEventFilter(self)
elif event.type() == QtCore.QEvent.ParentChange:
self.widget.window().installEventFilter(self)
if obj is self.widget.window() and event.type() == QtCore.QEvent.Resize:
geom = self.widget.geometry()
geom.moveBottomRight(QtCore.QPoint(event.size().width(), event.size().height()))
self.widget.setGeometry(geom)
return super().eventFilter(obj, event)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.copy_btn = QtWidgets.QPushButton(self)
self.copy_btn.setText("Copy")
resizer = Resizer(self.copy_btn)
self.resize(640, 480)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

Have QScrollArea react on wheelEvent, also in space taken up by children?

Consider this example:
#!/usr/bin/env python
import sys,os
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
class ScrollAreaWheel(QtWidgets.QScrollArea): # SO:9475772
def __init__(self, parent=None):
super(MainWindow.ScrollAreaWheel, self).__init__(parent)
self.parent = parent
def wheelEvent(self, event):
print("wheelEvent", event.angleDelta().y())
def __init__(self):
#~ self.do_init = QtCore.QEvent.registerEventType()
QtWidgets.QMainWindow.__init__(self)
self.setMinimumWidth(1000)
self.setMinimumHeight(400)
self.frame1 = QtWidgets.QFrame(self)
self.frame1.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame1layout = QtWidgets.QGridLayout(self.frame1)
self.frame1layout.setSpacing(0);
self.frame1layout.setContentsMargins(0,0,0,0);
self.frame1widget = QtWidgets.QWidget()
self.frame1widget.setLayout(QtWidgets.QGridLayout())
self.frame1layout.addWidget(self.frame1widget)
self.frame1scroll = MainWindow.ScrollAreaWheel(self) #QtWidgets.QScrollArea()
self.frame1scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.frame1scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.frame1widget.layout().addWidget(self.frame1scroll, 0, 0) #, Qt.AlignCenter)
#self.frame1scrolllayout = QtWidgets.QHBoxLayout(self.frame1scroll)
self.frame1scrolllayout = QtWidgets.QGridLayout(self.frame1scroll)
self.frame1scroll.setWidget(self.frame1scrolllayout.widget())
self.frame1scroll.setWidgetResizable(True)
self.frame1scroll.setAlignment(Qt.AlignCenter)
self.frame1label = QtWidgets.QLabel()
self.frame1scrolllayout.addWidget(self.frame1label, 0, 0, Qt.AlignCenter) ##
pixmap = QtGui.QPixmap(200, 100)
pixmap.fill(Qt.red)
self.frame1label.setPixmap(pixmap)
self.frame2 = QtWidgets.QFrame(self)
self.frame2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame2layout = QtWidgets.QHBoxLayout(self.frame2)
self.frame2layout.setSpacing(0);
self.frame2layout.setContentsMargins(0,0,0,0);
self.frame2scroll = QtWidgets.QScrollArea(self)
self.frame2scroll.setWidgetResizable(True)
self.frame2widget = QtWidgets.QWidget()
self.frame2widget.setLayout(QtWidgets.QGridLayout())
self.frame2scroll.setWidget(self.frame2widget)
self.frame2layout.addWidget(self.frame2scroll)
self.mainwid = QtWidgets.QWidget()
self.mainwid.setLayout(QtWidgets.QGridLayout())
self.setCentralWidget(self.mainwid)
self.splitter1 = QtWidgets.QSplitter(Qt.Horizontal)
self.splitter1.addWidget(self.frame1)
self.splitter1.addWidget(self.frame2)
self.splitter1.setSizes([600, 600]); # equal splitter at start
self.mainwid.layout().addWidget(self.splitter1)
self.mainwid.layout().update()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
main = MainWindow()
main.show()
sys.exit(app.exec_())
It generates this (Ubuntu 18.04):
I want to use mousewheel only on the left QScrollArea, for which I've made a separate class. However, its wheelEvent fires only when I'm outside the red box, not when I hover over it. How can I make ScrollAreaWheel.wheelEvent fire even when mouse is over the child label (the red box)?
You are the QLabel placing on top of the QScrollArea instead of placing it inside, visually it is the same but at the level of events it is not.
from PyQt5 import QtCore, QtGui, QtWidgets
class ScrollAreaWheel(QtWidgets.QScrollArea):
def wheelEvent(self, event):
print("wheelEvent", event.angleDelta().y())
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setMinimumSize(1000, 400)
frame1 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.StyledPanel)
scrollarea1 = ScrollAreaWheel(widgetResizable=True)
scrollarea1.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scrollarea1.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
widget1 = QtWidgets.QWidget()
scrollarea1.setWidget(widget1)
label_lay = QtWidgets.QGridLayout(widget1)
lay1 = QtWidgets.QVBoxLayout(frame1)
lay1.addWidget(scrollarea1)
pixmap = QtGui.QPixmap(200, 100)
pixmap.fill(QtCore.Qt.red)
label = QtWidgets.QLabel(pixmap=pixmap)
label_lay.addWidget(label, 0, 0, QtCore.Qt.AlignCenter)
#==============================
frame2 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.StyledPanel)
scrollarea2 = QtWidgets.QScrollArea(widgetResizable=True)
scrollarea2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scrollarea2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
widget2 = QtWidgets.QWidget()
scrollarea2.setWidget(widget2)
splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
splitter.addWidget(frame1)
splitter.addWidget(frame2)
splitter.setSizes([600, 600])
self.setCentralWidget(splitter)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

QListView Selected Index not updated when embedding a QWidget

I have embedded a QPushbutton in a Qwidget in a QListView:
QPushbutton >> QWidget >> QListView
list_widget = QWidget()
list_widget.layout(QHBoxLayout())
btn = QPushButton()
btn.pressed.connect(clicked)
list_widget.layout().addWidget(QPushButton())
list_view.setIndexWidget(self.list_model.index(row, 0), list_widget)
def clicked():
row = list_view.selectedIndexes()
The problem is now list_view.selectedIndexes() does not return the row of the pressed button, when pressed.
This seems to work only when the QPushbutton is embedded in the QListView directly: QPushbutton >> QListView.
Does anyone have an idea how to delegate the focus of the pushbutton to the QListView?
When you click on the button it is not transmitted to the QListView because the button consumes it and does not transmit it to other widgets so if you want to obtain the row it must be obtained indirectly, a possible solution is to use the geometry for it you must obtain the sender , in this case the button, and then for its topleft to global positions, then convert it to a local position with respect to the viewport of QListView, using that position with the method indexAt() you get the QModelIndex.
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.list_model = QtGui.QStandardItemModel(200, 1)
self.list_view = QtWidgets.QListView()
self.list_view.setModel(self.list_model)
self.setCentralWidget(self.list_view)
for row in range(self.list_model.rowCount()):
list_widget = QtWidgets.QWidget()
hlay = QtWidgets.QHBoxLayout(list_widget)
btn = QtWidgets.QPushButton(str(row))
btn.pressed.connect(self.clicked)
hlay.addWidget(btn)
hlay.setContentsMargins(0, 0, 0, 0)
self.list_view.setIndexWidget(self.list_model.index(row, 0), list_widget)
#QtCore.pyqtSlot()
def clicked(self):
btn = self.sender()
gp = btn.mapToGlobal(QtCore.QPoint())
lp = self.list_view.viewport().mapFromGlobal(gp)
ix = self.list_view.indexAt(lp)
print("row", ix.row())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Another much simpler way is to pass the row as an argument using functools.partial():
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.list_model = QtGui.QStandardItemModel(200, 1)
self.list_view = QtWidgets.QListView()
self.list_view.setModel(self.list_model)
self.setCentralWidget(self.list_view)
for row in range(self.list_model.rowCount()):
list_widget = QtWidgets.QWidget()
hlay = QtWidgets.QHBoxLayout(list_widget)
btn = QtWidgets.QPushButton(str(row))
btn.pressed.connect(partial(self.clicked, row))
hlay.addWidget(btn)
hlay.setContentsMargins(0, 0, 0, 0)
self.list_view.setIndexWidget(self.list_model.index(row, 0), list_widget)
#QtCore.pyqtSlot(int)
def clicked(self, row):
print(row)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Or using a lambda method:
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.list_model = QtGui.QStandardItemModel(200, 1)
self.list_view = QtWidgets.QListView()
self.list_view.setModel(self.list_model)
self.setCentralWidget(self.list_view)
for row in range(self.list_model.rowCount()):
list_widget = QtWidgets.QWidget()
hlay = QtWidgets.QHBoxLayout(list_widget)
btn = QtWidgets.QPushButton(str(row))
btn.pressed.connect(lambda *args, row=row: self.clicked(row))
hlay.addWidget(btn)
hlay.setContentsMargins(0, 0, 0, 0)
self.list_view.setIndexWidget(self.list_model.index(row, 0), list_widget)
#QtCore.pyqtSlot(int)
def clicked(self, row):
print(row)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
In my case I prefer to use partials since you do not need to write a lot of logic and it's thread-safe.

How to focus view on QLabel

I want to find QLabel with specific text and focus view on it. Finding widget with desired text is easy, but I couldn't figure out how to focus view on it.
The code so far looks like this:
import sys
from PySide import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super().__init__()
widget = QtGui.QWidget()
self.layout = QtGui.QGridLayout()
for i in range(10):
label = QtGui.QLabel("aaaa" + str(i))
self.layout.addWidget(label, i, 0)
widget.setLayout(self.layout)
self.toolbar = self.addToolBar("aa")
findAction = QtGui.QAction('Find', self)
findAction.triggered.connect(self.find)
self.toolbar.addAction(findAction)
self.scroll = QtGui.QScrollArea()
self.scroll.setWidget(widget)
self.scroll.setWidgetResizable(True)
self.setMaximumSize(200, 200)
self.setCentralWidget(self.scroll)
def find(self):
widgets = (self.layout.itemAt(i).widget() for i in range(self.layout.count()))
for w in widgets:
if isinstance(w, QtGui.QLabel):
if w.text() == "aaaa9":
w.setFocus()
def main():
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
app.exec_()
if __name__ == "__main__":
main()
Any ideas how to get focus working?
You can use ensureWidgetVisible()
self.scroll.ensureWidgetVisible(w)

Python: How to to query a current Tab from QTabWidget

A simple dialog with three tabs: 'Tab_01', 'Tab_02' and 'Tab_03'.
Pressing 'What Tab?' button should print what tab is currently active.
How to achieve it? (example code posted below):
from PyQt4 import QtGui, QtCore
import sys, os
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
mainWidget=QtGui.QWidget()
self.setCentralWidget(mainWidget)
mainLayout = QtGui.QVBoxLayout()
mainWidget.setLayout(mainLayout)
self.tabWidget = QtGui.QTabWidget()
mainLayout.addWidget(self.tabWidget)
self.tabWidget.connect(self.tabWidget, QtCore.SIGNAL("currentChanged(int)"), self.tabSelected)
myBoxLayout = QtGui.QVBoxLayout()
self.tabWidget.setLayout(myBoxLayout)
self.tabWidget.addTab(QtGui.QWidget(),'Tab_01')
self.tabWidget.addTab(QtGui.QWidget(),'Tab_02')
self.tabWidget.addTab(QtGui.QWidget(),'Tab_03')
ButtonBox = QtGui.QGroupBox()
ButtonsLayout = QtGui.QHBoxLayout()
ButtonBox.setLayout(ButtonsLayout)
Button_01 = QtGui.QPushButton("What Tab?")
ButtonsLayout.addWidget(Button_01)
Button_01.clicked.connect(self.whatTab)
mainLayout.addWidget(ButtonBox)
def tabSelected(self, arg=None):
print '\n\t tabSelected():', arg
def whatTab(self):
print '\n\t current Tab:', '?'
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
As you can see here QTabWidget has methods currentIndex and currentWidget.
Here is the solution (thanks Hyperboreus !):
from PyQt4 import QtGui, QtCore
import sys, os
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
mainWidget=QtGui.QWidget()
self.setCentralWidget(mainWidget)
mainLayout = QtGui.QVBoxLayout()
mainWidget.setLayout(mainLayout)
self.tabWidget = QtGui.QTabWidget()
mainLayout.addWidget(self.tabWidget)
self.tabWidget.connect(self.tabWidget, QtCore.SIGNAL("currentChanged(int)"), self.tabSelected)
myBoxLayout = QtGui.QVBoxLayout()
self.tabWidget.setLayout(myBoxLayout)
self.tabWidget.addTab(QtGui.QWidget(),'Tab_01')
self.tabWidget.addTab(QtGui.QWidget(),'Tab_02')
self.tabWidget.addTab(QtGui.QWidget(),'Tab_03')
ButtonBox = QtGui.QGroupBox()
ButtonsLayout = QtGui.QHBoxLayout()
ButtonBox.setLayout(ButtonsLayout)
Button_01 = QtGui.QPushButton("What Tab?")
ButtonsLayout.addWidget(Button_01)
Button_01.clicked.connect(self.whatTab)
mainLayout.addWidget(ButtonBox)
def tabSelected(self, arg=None):
print '\n\t tabSelected() current Tab index =', arg
def whatTab(self):
currentIndex=self.tabWidget.currentIndex()
currentWidget=self.tabWidget.currentWidget()
print '\n\t Query: current Tab index =', currentIndex
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())

Categories

Resources