Using qHelpEngine - python

I want to make a help file using QtHelp and QHelpEngine. I currently have some code but I am not sure about my errors and the documentation is a little vague in my opinion. Nonetheless the current issue I am facing is one of connecting signal and slots. The error I currently get is AttributeError: 'builtin_function_or_method' object has no attribute 'linkActivated' Not sure the reason for this as the documentation states that contentWidget does have a signal called linkActivated. And an error occurs here textViewer = QtWidgets.QTextBrowser(helpEngine)
Reference
from PyQt5 import QtCore, QtGui, QtWidgets, QtHelp
import os
class Ui_HelpSetupClass(QtWidgets.QDockWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
def setupUi(self, HelpSetupClass):
qUrl = "qthelp://ut.tool.help/tool/index.html"
HELP_DIR = os.getcwd()
HELP_PATH = HELP_DIR + "\\" + "Help" + "\\" + "help_file.qhc"
helpEngine = QtHelp.QHelpEngine(HELP_PATH)
helpEngine.setupData()
tableWidget = QtWidgets.QTabWidget()
tableWidget.setMaximumWidth(200)
tableWidget.addTab(helpEngine.contentWidget(), "Contents")
tableWidget.addTab(helpEngine.indexWidget(), "Index")
textViewer = QtWidgets.QTextBrowser(helpEngine)
textViewer.setSource(qUrl)
helpEngine.contentWidget.linkActivated(qUrl ).connect(textViewer.setSource(qUrl))
helpEngine.indexWidget.documentActivated(qUrl ).connect(textViewer.setSource(qUrl))
horizSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
horizSplitter.insertWidget(0, tableWidget)
horizSplitter.insertWidget(1, textViewer)
horizSplitter.hide()
helpWindow = QtWidgets.QDockWidget("Help", self)
helpWindow.setWidget(horizSplitter)
helpWindow.hide()
QtWidgets.QMainWindow.addDockWidget(QtCore.Qt.BottomDockWidgetArea, helpWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_HelpSetupClass()
ui.show()
sys.exit(app.exec_())

In your translation of the C++ code to Python it shows many errors so I will avoid pointing it out and I will only show the correct translation:
import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtHelp
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class HelpBrowser(QtWidgets.QTextBrowser):
def __init__(self, helpEngine, parent=None):
super().__init__(parent)
self.helpEngine = helpEngine
def loadResource(self, _type, name):
if name.scheme() == "qthelp":
return self.helpEngine.fileData(name)
else:
return super().loadResource(_type, name)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.scene = QtWidgets.QGraphicsScene()
self.scene.setSceneRect(0, 0, 400, 200)
self.view = QtWidgets.QGraphicsView(self.scene)
self.view.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
self.view.setRenderHints(QtGui.QPainter.Antialiasing)
self.setCentralWidget(self.view)
self.createHelpWindow()
self.createActions()
self.createMenus()
self.createConnections()
self.setWindowTitle(self.tr("QGraphicsScene Help Example"))
self.resize(640, 480)
def createHelpWindow(self):
self.helpEngine = QtHelp.QHelpEngine(
os.path.join(CURRENT_DIR, "documentation", "qgraphicshelpexample.qhc")
)
self.helpEngine.setupData()
tWidget = QtWidgets.QTabWidget()
tWidget.setMaximumWidth(200)
tWidget.addTab(self.helpEngine.contentWidget(), "Contents")
tWidget.addTab(self.helpEngine.indexWidget(), "Index")
textViewer = HelpBrowser(self.helpEngine)
textViewer.setSource(
QtCore.QUrl("qthelp://walletfox.qt.helpexample/doc/index.html")
)
self.helpEngine.setUsesFilterEngine(True)
self.helpEngine.contentWidget().linkActivated.connect(textViewer.setSource)
self.helpEngine.indexWidget().linkActivated.connect(textViewer.setSource)
horizSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
horizSplitter.insertWidget(0, tWidget)
horizSplitter.insertWidget(1, textViewer)
horizSplitter.hide()
self.helpWindow = QtWidgets.QDockWidget(self.tr("Help"), self)
self.helpWindow.setWidget(horizSplitter)
self.helpWindow.hide()
self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.helpWindow)
def createActions(self):
self.insertEllipseAction = QtWidgets.QAction(self.tr("Insert &Ellipse"), self)
self.insertEllipseAction.setIcon(QtGui.QIcon(":/icons/ellipse.png"))
self.insertRectangleAction = QtWidgets.QAction(
self.tr("Insert &Rectangle"), self
)
self.insertRectangleAction.setIcon(QtGui.QIcon(":/icons/rectangle.png"))
self.helpAction = QtWidgets.QAction(self.tr("Help Contents..."), self)
self.helpAction.setShortcut(QtGui.QKeySequence.HelpContents)
self.aboutAction = QtWidgets.QAction(self.tr("&About"), self)
def createMenus(self):
self.itemMenu = QtWidgets.QMenu(self.tr("&Item"), self)
self.itemMenu.addAction(self.insertEllipseAction)
self.itemMenu.addAction(self.insertRectangleAction)
self.helpMenu = QtWidgets.QMenu(self.tr("&Help"), self)
self.helpMenu.addAction(self.helpAction)
self.helpMenu.addAction(self.aboutAction)
self.menuBar().addMenu(self.itemMenu)
self.menuBar().addMenu(self.helpMenu)
def insertItem(self):
action = self.sender()
if isinstance(action, QtWidgets.QAction):
itemToAdd = None
mPen = QtGui.QPen(QtCore.Qt.black, 3, QtCore.Qt.SolidLine)
eBrush = QtGui.QBrush(QtGui.QColor("#FF7F50"))
rBrush = QtGui.QBrush(QtGui.QColor("#CC0000"))
if action.iconText() == "Insert Ellipse":
itemToAdd = self.scene.addEllipse(0, 0, 150, 75, mPen, eBrush)
elif action.iconText() == "Insert Rectangle":
itemToAdd = self.scene.addRect(0, 0, 100, 100, mPen, rBrush)
if itemToAdd is not None:
itemToAdd.setFlags(
QtWidgets.QGraphicsItem.ItemIsSelectable
| QtWidgets.QGraphicsItem.ItemIsMovable
)
def about(self):
QtWidgets.QMessageBox.about(
self,
self.tr("About QGraphicsScene Help Example"),
self.tr(
"This example demonstrates how to implement\n"
"help for a Qt application."
),
)
def createConnections(self):
self.insertEllipseAction.triggered.connect(self.insertItem)
self.insertRectangleAction.triggered.connect(self.insertItem)
self.helpAction.triggered.connect(self.helpWindow.show)
self.aboutAction.triggered.connect(self.about)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_A:
for item in self.scene.selectedItems():
self.scene.removeItem(item)
else:
super().keyPressEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Note: Using the original file "qgraphicshelpexample.qhp" causes me errors since the "./foo" paths like "./insertobject.html" are not resolved correctly so I change them to "foo".
The complete example can be found here.

Related

In PyQt5's QListWidget, how can I only show the tooltip for an item when the user chooses it?

I was inspired by this repo to add custom tooltip text to items when they are added to the QListWidget. However, I only want the tooltip message to appear when the item is chosen. How would I implement this?
Here is a GUI example that I have to test this feature:
import serial, time, sys
import serial.tools.list_ports
from PyQt5 import QtGui, QtWidgets, QtCore
import json, time
class GUI(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.__init_ui()
def closeEvent(self, event):
super().closeEvent(event)
def __init_ui(self):
self.setWindowTitle('QListWidgetToolTipDemo')
self.history_log = HistoryList()
self.history_log.itemDoubleClicked.connect(self.history_item_selected)
self.history_log.returnPressed.connect(self.history_item_selected)
self.history_log.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.line_edit = QtWidgets.QLineEdit()
self.line_edit.returnPressed.connect(self.populate_history)
self.middle_layout = QtWidgets.QHBoxLayout()
self.middle_layout.addWidget(self.history_log)
self.middle_layout.addWidget(self.line_edit)
middle_layout_wrapper = QtWidgets.QWidget()
middle_layout_wrapper.setLayout(self.middle_layout)
middle_layout_wrapper.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
# Sets full GUI layout
gui_layout = QtWidgets.QVBoxLayout()
gui_layout.addWidget(middle_layout_wrapper)
gui_layout.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop)
gui_layout.setContentsMargins(QtCore.QMargins(0, 0, 0, 0))
self.setLayout(gui_layout)
def populate_history(self):
self.history_log.addItem(self.line_edit.text())
self.line_edit.clear()
def history_item_selected(self):
self.line_edit.setText(self.history_log.currentItem().text())
class HistoryList(QtWidgets.QListWidget):
returnPressed = QtCore.pyqtSignal()
def __init__(self) -> None:
super().__init__()
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setMouseTracking(True)
self.itemEntered.connect(self.__showToolTip)
def keyPressEvent(self, ev):
super().keyPressEvent(ev)
if ev.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.returnPressed.emit()
def addItem(self, aitem) -> None:
item = ''
text = ''
if isinstance(aitem, str):
item = QtWidgets.QListWidgetItem()
text = aitem
item.setText(text)
elif isinstance(aitem, QtWidgets.QListWidgetItem):
item = aitem
text = item.text()
self.setItemWidget(item, QtWidgets.QWidget())
super().addItem(item)
def __showToolTip(self, item: QtWidgets.QListWidgetItem):
text = item.text()
text_width = self.fontMetrics().boundingRect(text).width()
width = self.width()
info = {"time":str(time.time()), "entry":text}
info = json.dumps(info, indent=4)
item.setToolTip(info)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
console = GUI()
screensize = app.desktop().availableGeometry().size()
console.show()
exit(app.exec_())
Currently, the following is how a tooltip works for any item:
Example where only display tooltip when item is selected:
Expanding on the suggestion from musicamante in the comments, I was able to get tooltip to display only for the selected item by overriding the event method and watch for a tooltip event (inspired from this SO post)
import serial, time, sys
import serial.tools.list_ports
from PyQt5 import QtGui, QtWidgets, QtCore
import json, time
class GUI(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.__init_ui()
def closeEvent(self, event):
super().closeEvent(event)
def __init_ui(self):
self.setWindowTitle('QListWidgetToolTipDemo')
self.history_log = HistoryList()
self.history_log.itemDoubleClicked.connect(self.history_item_selected)
self.history_log.returnPressed.connect(self.history_item_selected)
self.history_log.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.line_edit = QtWidgets.QLineEdit()
self.line_edit.returnPressed.connect(self.populate_history)
self.middle_layout = QtWidgets.QHBoxLayout()
self.middle_layout.addWidget(self.history_log)
self.middle_layout.addWidget(self.line_edit)
middle_layout_wrapper = QtWidgets.QWidget()
middle_layout_wrapper.setLayout(self.middle_layout)
middle_layout_wrapper.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
# Sets full GUI layout
gui_layout = QtWidgets.QVBoxLayout()
gui_layout.addWidget(middle_layout_wrapper)
gui_layout.setAlignment(QtCore.Qt.AlignmentFlag.AlignTop)
gui_layout.setContentsMargins(QtCore.QMargins(0, 0, 0, 0))
self.setLayout(gui_layout)
def populate_history(self):
self.history_log.addItem(self.line_edit.text())
self.line_edit.clear()
def history_item_selected(self):
self.line_edit.setText(self.history_log.currentItem().text())
class HistoryList(QtWidgets.QListWidget):
returnPressed = QtCore.pyqtSignal()
def __init__(self) -> None:
super().__init__()
self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.setMouseTracking(True)
self.itemEntered.connect(self.__addToolTip)
self.items_tooltip_info_dict = dict()
def keyPressEvent(self, ev):
super().keyPressEvent(ev)
if ev.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.returnPressed.emit()
def event(self, e: QtCore.QEvent) -> bool:
if e.type() == QtCore.QEvent.ToolTip:
if not self.selectedItems():
QtWidgets.QToolTip.hideText()
return True
else:
index = self.indexFromItem(self.currentItem()).row()
info = json.dumps(self.items_tooltip_info_dict[index], indent=4)
QtWidgets.QToolTip.showText(e.globalPos(),info)
e.accept()
return super().event(e)
def addItem(self, aitem) -> None:
item = ''
text = ''
if isinstance(aitem, str):
item = QtWidgets.QListWidgetItem()
text = aitem
item.setText(text)
elif isinstance(aitem, QtWidgets.QListWidgetItem):
item = aitem
text = item.text()
self.setItemWidget(item, QtWidgets.QWidget())
super().addItem(item)
def __addToolTip(self, item: QtWidgets.QListWidgetItem):
text = item.text()
info = {"time":str(time.time()), "entry":text}
index = self.indexFromItem(item).row()
self.items_tooltip_info_dict[index] = info
if __name__ == "__main__":
app = QtWidgets.QApplication([])
console = GUI()
screensize = app.desktop().availableGeometry().size()
console.show()
exit(app.exec_())

PyQt - Program to close window with model and view

Can anyone help me make a good code write and help me to understand the SIGNAL and SLOT with Model and View.
With easy examples and codes i am new in Python and Qt5 and i try to learn in easy way.
I have books with me to learn faster but books do it more complicated to learn and don't do it step by step.
Thank you.
import sys
from PyQt5 import QtWidgets as qtW
from PyQt5 import QtCore as qtC
class Model(qtW.QWidget, qtC.QObject):
quit = qtC.pyqtSignal(bool)
message_quit = "GOODBYE !"
def exit_window(self):
print(self.message_quit)
self.quit.emit(self.close())
class View(qtW.QWidget):
message = "Tape Text Here !"
message_show = "Your message shown here !"
button_show = "SHOW"
button_quit = "QUIT"
message_quit = "GOODBYE !"
def __init__(self):
super().__init__()
self.grid = qtW.QGridLayout()
self.setLayout(self.grid)
self.message_lineEdit = qtW.QLineEdit(self.message)
self.grid.addWidget(self.message_lineEdit, 0, 0)
self.message_label = qtW.QLabel(self.message_show)
self.grid.addWidget(self.message_label, 1, 0)
self.quit_button = qtW.QPushButton(self.button_quit)
self.grid.addWidget(self.quit_button, 2, 0)
class MainWindow(qtW.QMainWindow):
def __init__(self):
super().__init__()
self.view = View()
self.setCentralWidget(self.view)
self.model = Model()
self.view.quit_button.clicked.connect(self.model.exit_window)
self.show()
if __name__ == '__main__':
app = qtW.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())
The signal / pyqtSignal() must be created at the origin, in this case in View() and not in Model(). Just like the issue / emit(), it must also be put at the origin.
import sys
from PyQt5 import QtWidgets as qtW
from PyQt5 import QtCore as qtC
class Model(qtW.QWidget, qtC.QObject):
#quit = qtC.pyqtSignal(bool)
message_quit = "GOODBYE !"
def exit_window(self, bool):
print(self.message_quit)
#self.quit.emit(self.close())
class View(qtW.QWidget):
signEmit1 = qtC.pyqtSignal(bool)
message = "Tape Text Here !"
message_show = "Your message shown here !"
button_show = "SHOW"
button_quit = "QUIT"
message_quit = "GOODBYE !"
def __init__(self):
super().__init__()
self.grid = qtW.QGridLayout()
self.setLayout(self.grid)
self.message_lineEdit = qtW.QLineEdit(self.message)
self.grid.addWidget(self.message_lineEdit, 0, 0)
self.message_label = qtW.QLabel(self.message_show)
self.grid.addWidget(self.message_label, 1, 0)
self.quit_button = qtW.QPushButton(self.button_quit)
self.grid.addWidget(self.quit_button, 2, 0)
self.quit_button.clicked.connect(self.btnAction)
def btnAction(self):
self.signEmit1.emit(True)
class MainWindow(qtW.QMainWindow):
def __init__(self):
super().__init__()
self.model = Model()
self.view = View()
self.view.signEmit1.connect(self.model.exit_window)
self.setCentralWidget(self.view)
self.show()
if __name__ == '__main__':
app = qtW.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())
Hope this helps

pyside2 how to query and create and delete dynamic widget

layout
layout (1)
QlineEdit
Qpushbutton
layout (2)
QlineEdit
Qpushbutton
Qpushbutton (3)
I try to create and delete layout(1,2) in layout.
it's work real time. layout(1,2) are dynamic number (1,2,3,~~)
Qpushbutton click -> parent layout and widget delete
and query text in QlineEdit
my test code --
#-*- coding:utf-8 -*-
import maya.cmds as mc
import os
import pprint
from PySide2 import QtWidgets, QtCore, QtGui
class PreferenceUI(QtWidgets.QDialog):
def __init__(self):
super(PreferenceUI, self).__init__()
self.setWindowTitle("preference")
self.create_widgets()
self.create_layouts()
self.create_connections()
self.load_department()
def create_widgets(self):
self.departmentNameLine = QtWidgets.QLineEdit()
self.departmentNameLine.setFixedSize(100,20)
self.departmentPathLine = QtWidgets.QLineEdit()
self.departmentMinusBtn = QtWidgets.QPushButton("-")
self.departmentMinusBtn.setFixedSize(20,20)
self.departmentPlusBtn = QtWidgets.QPushButton("+")
self.sysAppendWidget = QtWidgets.QTextEdit()
def create_layouts(self):
self.mainLayout = QtWidgets.QFormLayout(self)
self.departmentLayout = QtWidgets.QVBoxLayout()
self.departmentLastLayout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(self.departmentLastLayout)
self.departmentLayout.addWidget(self.departmentPlusBtn)
self.mainLayout.addRow("department :", self.departmentLayout)
self.mainLayout.insertRow(self.mainLayout.count()-1, "sys.path.append :", self.sysAppendWidget)
def create_connections(self):
pass
def load_department(self):
self.departmentPlusBtn.setParent(None)
jsonDict = {"department": [["temp", "tempPath"], ["temp2", "temp2Path"]]}
for i in range(len(jsonDict["department"])):
layout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(layout)
departmentNameLine = QtWidgets.QLineEdit()
departmentNameLine.setText(jsonDict["department"][i][0])
departmentNameLine.setFixedSize(100,20)
departmentPathLine = QtWidgets.QLineEdit()
departmentPathLine.setText(jsonDict["department"][i][1])
departmentMinusBtn = QtWidgets.QPushButton("-")
departmentMinusBtn.setFixedSize(20,20)
cnt = self.departmentLayout.count()
departmentMinusBtn.clicked.connect(lambda x:self.remove_department(cnt))
layout.addWidget(departmentNameLine)
layout.addWidget(departmentPathLine)
layout.addWidget(departmentMinusBtn)
self.departmentLayout.insertWidget(self.departmentLayout.count(), self.departmentPlusBtn)
def remove_department(self, index):
print index
print self.departmentLayout.children()[0].layout().children()
if __name__ == "__main__":
try:
ui.close
except:
pass
ui = PreferenceUI()
ui.show()
I want
add path line
delete path line
query departmentNameLine, departmentPathLine text
i try ↑, but fail
i try in maya
To keep the logic tidy I have created a class that represents a row, then store the rows in a list to get the texts or to delete the row as I show below:
from functools import partial
from PySide2 import QtWidgets, QtCore, QtGui
class Widget(QtWidgets.QWidget):
def __init__(self, text1, text2, parent=None):
super().__init__(parent)
self.departmentNameLine = QtWidgets.QLineEdit(text1)
self.departmentNameLine.setFixedSize(100, 20)
self.departmentPathLine = QtWidgets.QLineEdit(text2)
self.departmentMinusBtn = QtWidgets.QPushButton("-")
self.departmentMinusBtn.setFixedSize(20, 20)
self.setContentsMargins(0, 0, 0, 0)
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.departmentNameLine)
layout.addWidget(self.departmentPathLine)
layout.addWidget(self.departmentMinusBtn)
class PreferenceUI(QtWidgets.QDialog):
def __init__(self):
super(PreferenceUI, self).__init__()
self.widgets = []
self.setWindowTitle("preference")
self.create_widgets()
self.create_layouts()
self.create_connections()
self.load_department()
def create_widgets(self):
self.departmentPlusBtn = QtWidgets.QPushButton("+")
self.sysAppendWidget = QtWidgets.QTextEdit()
def create_layouts(self):
self.mainLayout = QtWidgets.QFormLayout(self)
self.departmentLayout = QtWidgets.QVBoxLayout()
self.departmentLastLayout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(self.departmentLastLayout)
self.departmentLayout.addWidget(self.departmentPlusBtn)
self.mainLayout.addRow("department :", self.departmentLayout)
self.mainLayout.insertRow(
self.mainLayout.count() - 1, "sys.path.append :", self.sysAppendWidget
)
def create_connections(self):
self.departmentPlusBtn.clicked.connect(self.add_row)
def load_department(self):
jsonDict = {"department": [["temp", "tempPath"], ["temp2", "temp2Path"]]}
for text1, text2 in jsonDict["department"]:
self.create_row(text1, text2)
def save_departament(self):
l = []
for widget in self.widgets:
l.append([self.departmentNameLine.text(), self.departmentPathLine.text()])
jsonDict = {"department": l}
print(jsonDict)
def add_row(self):
self.create_row("text1", "text2")
def create_row(self, text1="", text2=""):
widget = Widget(text1, text2)
widget.departmentMinusBtn.clicked.connect(partial(self.delete, widget))
self.departmentLayout.addWidget(widget)
self.widgets.append(widget)
def delete(self, widget):
if widget in self.widgets:
self.widgets.remove(widget)
widget.deleteLater()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = PreferenceUI()
w.show()
sys.exit(app.exec_())

PyQt5 - resize (limit maximum size) input dialog

I read this: How to resize QInputDialog, PyQt but it didnt work for me, as it seems to be about PyQt4
This is my code snipplet:
def ImportURL(self): #URL dialog aufrufen
InputDialog = QtWidgets.QInputDialog(self)
i, okPressed = InputDialog.getText(self, "Import website", "Site to import:", QtWidgets.QLineEdit.Normal, "https://de.wikipedia.org/wiki/Wikipedia:Hauptseite")
if okPressed:
self.getWebsite(i)
And i tried adding .setFixedSize in the 2nd line. I tried adding InputDialog.setFixedSite(self) between line 2 and 3. Nothing worked, it either crashes or it creates a second, empty window. Am i overlooking something here?
In the answers to the other question do not explain the cause of the problem so in my answer will try to cover as much as possible
Explanation:
The getText() method is a static method, which means that an object is not used, in the method internally if it is used but it is not accessible. So the InputDialog that you create is not the one you show and this you can check using the following code since you will see 2 windows:
def ImportURL(self):
InputDialog = QtWidgets.QInputDialog(self)
InputDialog.show()
i, okPressed = InputDialog.getText(self, "Import website", "Site to import:", QtWidgets.QLineEdit.Normal, "https://de.wikipedia.org/wiki/Wikipedia:Hauptseite")
if okPressed:
self.getWebsite(i)
Solutions:
So there are the following solutions:
Taking advantage of what you have passed as a parent to self, you can obtain the object using findChildren:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
button = QtWidgets.QPushButton(
"Open QInputDialog", clicked=self.ImportURL
)
vlay = QtWidgets.QVBoxLayout(self)
vlay.addWidget(button)
#QtCore.pyqtSlot()
def ImportURL(self):
QtCore.QTimer.singleShot(0, self.after_show)
i, okPressed = QtWidgets.QInputDialog.getText(
self,
"Import website",
"Site to import:",
QtWidgets.QLineEdit.Normal,
"https://de.wikipedia.org/wiki/Wikipedia:Hauptseite",
)
if okPressed:
# self.getWebsite(i)
print(i)
#QtCore.pyqtSlot()
def after_show(self):
size = QtCore.QSize(500, 100)
for d in self.findChildren(QtWidgets.QInputDialog):
if d.isVisible():
d.resize(size)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Do not use the getText() method but create an object that implements the same logic:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
button = QtWidgets.QPushButton(
"Open QInputDialog", clicked=self.ImportURL
)
vlay = QtWidgets.QVBoxLayout(self)
vlay.addWidget(button)
#QtCore.pyqtSlot()
def ImportURL(self):
dialog = QtWidgets.QInputDialog(self)
dialog.resize(QtCore.QSize(500, 100))
dialog.setWindowTitle("Import website")
dialog.setLabelText("Site to Import")
dialog.setTextValue(
"https://de.wikipedia.org/wiki/Wikipedia:Hauptseite"
)
dialog.setTextEchoMode(QtWidgets.QLineEdit.Normal)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
i = dialog.textValue()
print(i)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Update:
The layout of the QInputDialog has QLayout::SetMinAndMaxSize set as sizeConstraint, so the fixed size will not work, the trick is to change it to QLayout::SetDefaultConstraint:
from functools import partial
# ...
#QtCore.pyqtSlot()
def ImportURL(self):
dialog = QtWidgets.QInputDialog(self)
dialog.setWindowTitle("Import website")
dialog.setLabelText("Site to Import")
dialog.setTextValue(
"https://de.wikipedia.org/wiki/Wikipedia:Hauptseite"
)
dialog.setTextEchoMode(QtWidgets.QLineEdit.Normal)
wrapper = partial(self.on_timeout, dialog)
QtCore.QTimer.singleShot(0, wrapper)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
i = dialog.textValue()
print(i)
def on_timeout(self, dialog):
lay = dialog.layout()
lay.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
dialog.setFixedSize(QtCore.QSize(500, 100))

PyQt4 : Connect splitter

I want to connect splitters to make a "cross" splitters between 4 widgets. I tried to do it using signal and slot between two splitters, and even if no errors occured, the behavior is not the one I hope (in fact nothing happens).
import sys
from PyQt4 import QtGui, QtCore
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.initUI()
self.window.setFocus()
self.setCentralWidget(self.window)
self.showMaximized()
def initUI(self) :
self.window = QtGui.QWidget()
self.editor1 = QtGui.QTextEdit()
self.editor2 = QtGui.QTextEdit()
self.editor3 = QtGui.QTextEdit()
self.editor4 = QtGui.QTextEdit()
self.split1 = QtGui.QSplitter()
self.split2 = QtGui.QSplitter()
self.split3 = QtGui.QSplitter()
self.split2.setOrientation(QtCore.Qt.Vertical)
self.split3.setOrientation(QtCore.Qt.Vertical)
self.split2.addWidget(self.editor1)
self.split2.addWidget(self.editor2)
self.split3.addWidget(self.editor3)
self.split3.addWidget(self.editor4)
self.connect(self.split2, QtCore.SIGNAL("splitterMoved"), self.split3.moveSplitter)
self.connect(self.split3, QtCore.SIGNAL("splitterMoved"), self.split2.moveSplitter)
self.split1.addWidget(self.split2)
self.split1.addWidget(self.split3)
self.layout = QtGui.QHBoxLayout()
self.layout.addWidget(self.split1)
self.window.setLayout(self.layout)
def main() :
qApp = QtGui.QApplication(sys.argv)
qApp.setStyle('cleanlooks')
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())
if __name__ == '__main__':
main()
Any ideas ?
Ok finally I found how to do that using python :
import sys
from PyQt4 import QtGui, QtCore
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("Cluster View")
self.initUI()
self.window.setFocus()
self.setCentralWidget(self.window)
self.showMaximized()
def splitterMoved(self, sender) :
print ("ok", sender)
receiver = self.split2 if sender is self.split3 else self.split3
receiver.blockSignals(True)
receiver.setSizes(sender.sizes())
receiver.blockSignals(False)
def initUI(self) :
self.window = QtGui.QWidget()
self.editor1 = QtGui.QTextEdit()
self.editor2 = QtGui.QTextEdit()
self.editor3 = QtGui.QTextEdit()
self.editor4 = QtGui.QTextEdit()
self.split1 = QtGui.QSplitter()
self.split2 = QtGui.QSplitter()
self.split3 = QtGui.QSplitter()
self.split2.setOrientation(QtCore.Qt.Vertical)
self.split3.setOrientation(QtCore.Qt.Vertical)
self.split2.addWidget(self.editor1)
self.split2.addWidget(self.editor2)
self.split3.addWidget(self.editor3)
self.split3.addWidget(self.editor4)
self.connect(self.split2, QtCore.SIGNAL("splitterMoved(int, int)"), lambda x : self.splitterMoved(self.split2))
self.connect(self.split3, QtCore.SIGNAL("splitterMoved(int, int)"), lambda x : self.splitterMoved(self.split3))
self.split1.addWidget(self.split2)
self.split1.addWidget(self.split3)
self.layout = QtGui.QHBoxLayout()
self.layout.addWidget(self.split1)
self.window.setLayout(self.layout)
def main() :
qApp = QtGui.QApplication(sys.argv)
qApp.setStyle('cleanlooks')
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())
if __name__ == '__main__':
main()
Maybe there are better way to do that, but at least it works now.

Categories

Resources