Send text to textbox from arbitrary object (Python and Qt) - python

I need to be able to send text from class "node" in node.py:
import datetime
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class node( QGraphicsItem ):
def __init__( self, position, scene ):
super( node, self ).__init__( None, scene )
self.setFlags( QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable )
self.rect = QRectF( -30, -30, 120, 60 )
self.setPos( position )
scene.clearSelection()
def sendFromNodeToBox( self, text ):
# how do i send text from here to textBox?
pass
def boundingRect( self ):
return self.rect
def paint( self, painter, option, widget ):
painter.setRenderHint( QPainter.Antialiasing )
pen = QPen( Qt.SolidLine )
pen.setColor( Qt.black )
pen.setWidth( 3 )
if option.state & QStyle.State_Selected:
#####################
self.sendFromNodeToBox( 'node selected' )
#####################
self.setZValue( 1 )
pen.setWidth( 4 )
pen.setColor( Qt.green )
else:
pen.setWidth( 3 )
self.setZValue( 0 )
painter.setPen( pen )
painter.setBrush( QColor( 200, 0, 0 ) )
painter.drawRoundedRect( self.rect, 10.0, 10.0 )
to statusBox in mainWindow.ui, which is being loaded by mainWindow.py
import os, sip, sys, subprocess, platform
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.uic import *
from PyQt4.QtOpenGL import *
from src.node import *
app = None
class mainWindow( QMainWindow ):
def __init__( self, parent = None ):
super( mainWindow, self ).__init__( parent )
self.currentPlatform = platform.system()
if self.currentPlatform == "Windows":
self.ui = loadUi( r'ui\mainWindow.ui', self )
elif self.currentPlatform == "Darwin":
self.ui = loadUi( r'ui/mainWindow.ui', self )
else:
print 'platform not supported'
quit()
# Scene view
self.scene = SceneView()
self.nodeDropGraphicsView.setViewport( QGLWidget( QGLFormat( QGL.SampleBuffers ) ) )
self.nodeDropGraphicsView.setScene( self.scene )
self.sendTextToBox( 'this text comes from mainWindow class, line 37 and 38.\n' )
self.sendTextToBox( 'press right mouse button.\n' )
def sendTextToBox( self, text ):
cursorBox = self.statusBox.textCursor()
cursorBox.movePosition(cursorBox.End)
cursorBox.insertText( str( text ) )
self.statusBox.ensureCursorVisible()
class SceneView( QGraphicsScene ):
def __init__( self, parent=None ):
super( SceneView, self ).__init__( parent )
text = self.addText( 'title' )
def mousePressEvent( self, event ):
pos = event.scenePos()
if event.button() == Qt.MidButton:
pass
elif event.button() == Qt.RightButton:
newNode = node( pos, self )
super( SceneView, self ).mousePressEvent( event )
def mouseReleaseEvent( self, event ):
print 'mouseReleaseEvent'
self.line = None
super( SceneView, self ).mouseReleaseEvent( event )
if __name__ == "__main__":
app = QApplication( sys.argv )
screenSize = QApplication.desktop().availableGeometry()
window = mainWindow()
window.resize( int( screenSize.width() ), int( screenSize.height() ) )
window.show()
app.exec_()
App runs on win and osx. Linux not tested yet.
Python 2.7 and Qt 4.8 required.
Any suggestions?
The full source is here:
https://www.dropbox.com/sh/lcetrurnemr2cla/AAD-Z6ijgTrG0qVU_cum5viua?dl=0
Help is being much appreciated.

One way to do this would be to define a custom signal on the SceneView class, and then the graphics item can emit the text via its scene:
class node( QGraphicsItem ):
...
def sendFromNodeToBox( self, text ):
self.scene().textMessage.emit(text)
class SceneView( QGraphicsScene ):
textMessage = pyqtSignal(str)
class mainWindow( QMainWindow ):
def __init__( self, parent = None ):
...
self.scene = SceneView()
self.scene.textMessage.connect(self.sendTextToBox)

Related

WxPython import widgets from other classes

I'm a beginner in WxPython and I've tried experimenting splitting up the code to make it organized and look neater. I've tried it with simple code but it doesn't work. Can anyone please give me a hand?
The code I've tried:
import wx
class text_ctrl ( wx.Panel ):
def __init ( self, parent ):
wx.Panel.__init__ ( self, parent = parent )
text = wx.TextCtrl ( self, pos = ( 100, 100 ) )
class Window ( wx.Frame ):
def __init__ ( self ):
super().__init__ ( parent = None, title = "Learn - Tab TextBox" )
panel = wx.Panel()
text_ctrl ( self )
self.Show()
if __name__ == "__main__":
app = wx.App()
window = Window()
app.MainLoop()
Problem: Textbox doesn't show up ( which is supposed to be the main point ).
For want of a nail the kingdom was lost
You are missing a __
Without the init, nothing occurs when you call text_ctrl
import wx
class text_ctrl ( wx.Panel ):
#def __init ( self, parent ):
def __init__ ( self, parent ):
wx.Panel.__init__ ( self, parent = parent )
text = wx.TextCtrl ( self, pos = ( 100, 100 ) )
class Window ( wx.Frame ):
def __init__ ( self ):
super().__init__ ( parent = None, title = "Learn - Tab TextBox" )
# panel = wx.Panel()
text_ctrl ( self )
self.Show()
if __name__ == "__main__":
app = wx.App()
window = Window()
app.MainLoop()

How to handle/override when the red x button in the corner is pressed in PyQt5 for QtWidget?

I have created a gui in PyQt5, and have several window-classes controlled by a class called Controller.
Background:
In one of the window(A) you can push buttons and a new window(B) pops up and A is disabled. Then when quit button is pressed from window B it goes back to window A without saving edits in window B and enables window A, and if continue button is pressed in B, then it reopens window A and enables it.
Problem:
However, when the x button in the corner of window B is pressed the window is closed and window A is disabled. My question is therefore: How can I make window A enable again when B is closed?
Can I override the red corner x event such that I can be able to enable window A again?
PS! I tried to make the code minimal and reproducible, let me know if there is something I should fix:)
import sys
from PyQt5 import QtCore, QtWidgets
class WindowTwo(QtWidgets.QWidget):
switch_window = QtCore.pyqtSignal()
def __init__(self, M, S):
QtWidgets.QWidget.__init__(self)
self.S = S
self.M = M
self.setupUi ( self )
self.setWindowTitle ( 'M' )
def setupUi(self, CM):
CM.setEnabled ( True )
CM.setFocusPolicy ( QtCore.Qt.TabFocus )
layout = QtWidgets.QGridLayout()
layout.addWidget(QtWidgets.QLabel("M: " ),0,0)
layout.addWidget(QtWidgets.QLabel("S: " ),0,1)
self.QuitButton = QtWidgets.QPushButton ( "Quit" )
self.QContinueButton = QtWidgets.QPushButton ( "Continue" )
self.QuitButton.clicked.connect ( CM.close )
self.QContinueButton.clicked.connect( lambda: self.windowtwo(self.M))
layout.addWidget( self.QuitButton, 10, 1 )
layout.addWidget ( self.QContinueButton, 10, 2 )
self.setLayout ( layout )
def windowtwo( self, M):
self.M = M
self.switch_window.emit()
class MS(QtWidgets.QWidget):
switch_window = QtCore.pyqtSignal(int)
def __init__(self, M, S):
QtWidgets.QWidget.__init__(self)
self.S = S
self.M = M
self.setupUi ( self )
self.setWindowTitle ( 'M' )
def setupUi(self, CM):
CM.setEnabled ( True )
CM.setFocusPolicy ( QtCore.Qt.TabFocus )
layout = QtWidgets.QGridLayout()
layout.addWidget(QtWidgets.QLabel("M: " ),0,0)
layout.addWidget(QtWidgets.QLabel("S: " ),0,1)
self.QWindowTwoButton = QtWidgets.QPushButton ( ' Go to other window')
self.QuitButton = QtWidgets.QPushButton ( "Quit" )
self.QContinueButton = QtWidgets.QPushButton ( "Continue" )
self.QuitButton.clicked.connect ( CM.close )
self.QWindowTwoButton.clicked.connect( lambda b=0, a= 400 : self.windowms(a))
layout.addWidget( self.QuitButton, 10, 1 )
layout.addWidget ( self.QContinueButton, 10, 2 )
layout.addWidget ( self.QWindowTwoButton, 10, 3 )
self.setLayout ( layout )
def windowms( self, a):
a = 100
self.switch_window.emit(a)
class Controller:
def __init__(self):
self.M = 5
self.S = 7
self.A = 8
# pass
def show_window_two(self):
self.window_two = WindowTwo(self.M, self.S)
self.window_two.switch_window.connect(self.show_window_three)
self.window_two.show()
def show_window_three(self):
try:
self.A = self.window_four.A
except:
pass
self.window_three = MS(self.M, self.S)
self.mscrollArea = QtWidgets.QScrollArea()
self.mscrollArea.setWidget(self.window_three)
self.mscrollArea.setDisabled(0)
self.window_three.switch_window.connect(self.show_window_four)
self.window_three.QuitButton.clicked.connect(self.mscrollArea.close)
self.mscrollArea.show()
self.mscrollArea.resize(700, 500)
self.mscrollArea.setWindowTitle("MS")
self.window_two.close()
try:
self.window_four.close()
except:
pass
def show_window_four(self, a):
if (a == 100):
self.window_four = WindowTwo(self.M, self.S)
self.window_four.switch_window.connect(self.show_window_three)
self.mscrollArea.setDisabled(1)
self.window_four.QuitButton.clicked.connect(lambda: self.window_four.close)
self.window_four.QuitButton.clicked.connect(lambda: self.mscrollArea.setDisabled(0))
self.window_four.show()
#Here is an else if a is other values to open other windows
def main():
app = QtWidgets.QApplication(sys.argv)
controller = Controller()
controller.show_window_two()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The closeEvent is fired whenever a widget is closed, for example by clicking the "X" in the corner. Just override it with your own code to show the main window again, or emit a signal to inform your Controller.
from PyQt5 import QtWidgets
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
class W1(QtWidgets.QWidget):
def closeEvent(self, event):
print("closing w1")
class W2(QtWidgets.QWidget):
def __init__(self, w1):
super().__init__()
self.w1 = w1
def closeEvent(self, event):
print("closing w2")
self.w1.show()
w1 = W1()
w2 = W2(w1)
w2.show()
app.exec_()

How to scroll line numbers in a QTextEdit

Here is my code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class Editor(QPlainTextEdit):
def __init__(self, parent):
super(Editor, self).__init__()
self.setPlainText( u'apple, banana\norange\nblah blah\n\nOh yeah!....\n'*2 )
self.setParent( parent )
self.setWordWrapMode( QTextOption.NoWrap )
self.setViewportMargins( 50,0,0,0 )
QObject.connect( self, SIGNAL("textChanged()"), self.repainting )
def repainting(self) : self.parent().update()
class WinE(QMainWindow):
def __init__(self, font=QFont( 'Monospace', 12 )):
super(WinE, self).__init__()
self.font = font
self.font.setFixedPitch( True )
self.ce = Editor( self )
self.ce.setFont( self.font )
self.setWindowTitle('Code Editor')
self.textr = QRect( 3, 5, self.ce.childrenRect().x() -12, self.ce.childrenRect().height() )
self.setGeometry( QRect(800, 840, 351, 250) )
self.setCentralWidget( self.ce )
self.show()
def paintEvent(self, event):
qp = QPainter ()
qp.begin ( self )
self.drawLiNums ( qp )
qp.end ()
def drawLiNums(self, qp):
qp.setPen ( QColor(255, 255, 255) )
qp.setFont ( self.font )
qp.drawText ( self.textr, Qt.AlignRight, self.lineNumeration() )
def lineNumeration(self):
return ''.join( [str(n+1) +'\n' for n in range( len(self.ce.toPlainText().splitlines(False)) )] )
def main():
app = QApplication(sys.argv)
ex = WinE()
sys.exit(app.exec_())
if __name__ == '__main__': main()
Editor shows up with numbers, and the numbers are updating when adding new lines. But when it reaches the end of the widget, the text continues to scroll while typing, but the line numbers stop updating, and there's no scrolling whatsoever on line number area!
I hope this solves your problem!
I simply called parent().update() every time the text is scrolled down. And I started the lineNumeration at the first visible line (line=block in qt)
Best wishes, MrP :)
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class Editor(QPlainTextEdit):
def __init__(self, parent):
super(Editor, self).__init__()
self.setPlainText( u'apple, banana\norange\nblah blah\n\nOh yeah!....\n'*6 )
self.setParent( parent )
self.setWordWrapMode( QTextOption.NoWrap )
self.setViewportMargins( 50,0,0,0 )
QObject.connect( self, SIGNAL("textChanged()"), self.repainting )
def repainting(self):
self.parent().update()
def scrollContentsBy(self, *args, **kwargs):
self.parent().update()
return QPlainTextEdit.scrollContentsBy(self, *args, **kwargs)
class WinE(QMainWindow):
def __init__(self, font=QFont( 'Monospace', 12 )):
super(WinE, self).__init__()
self.font = font
self.font.setFixedPitch( True )
self.ce = Editor( self )
self.ce.setFont( self.font )
self.setWindowTitle('Code Editor')
self.textr = QRect( 3, 5, self.ce.childrenRect().x() -12, self.ce.childrenRect().height() )
self.setGeometry( QRect(800, 840, 351, 250) )
self.setCentralWidget( self.ce )
self.show()
def paintEvent(self, event):
qp = QPainter ()
qp.begin ( self )
self.drawLiNums ( qp )
qp.end ()
def drawLiNums(self, qp):
qp.setPen ( QColor(255, 255, 255) )
qp.setFont ( self.font )
qp.drawText ( self.textr, Qt.AlignRight, self.lineNumeration() )
def lineNumeration(self):
offset=self.ce.firstVisibleBlock().firstLineNumber()
return ''.join(str(i)+"\n" for i in range(offset+1, self.ce.blockCount()+1))
def main():
app = QApplication(sys.argv)
ex = WinE()
sys.exit(app.exec_())
if __name__ == '__main__': main()

PySide: Add images to tooltips

I'm building a tool that lists files in a directory. When you hover over each file it shows a tooltip displaying the date and who made the file. I'd also like an image to accompany this data.
Is it possible to insert an image into a tooltip? For each item in the QTreeView I'd like a specific image and text to popup. If it can't be done with tooltips are there other alternatives?
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import maya.OpenMayaUI as mui
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
''' Classes '''
############################################
class Main_Window( QtGui.QDialog ):
def __init__( self, parent=get_parent() ):
super( Main_Window, self ).__init__( parent )
self.create_gui()
self.create_layout()
self.create_connections()
self.get_contents()
#--------------------------------------------------------------------
def create_gui( self ):
self.tv_model=MyModel()
self.tv_file_list = File_List( self )
#--------------------------------------------------------------------
def create_layout( self ):
self.main_layout = QtGui.QVBoxLayout( self )
self.main_layout.addWidget( self.tv_file_list )
self.setLayout( self.main_layout )
#--------------------------------------------------------------------
def get_contents(self):
self.tv_model.clear()
self.tv_model.setHorizontalHeaderLabels(["name","date"])
contents=["path1","path2"]
for path in contents:
date = self.get_date(path)
self.add_file(path,date)
self.tv_file_list.setColumnWidth(0, 150)
#--------------------------------------------------------------------
def add_file(self, name, date):
name = QtGui.QStandardItem(name)
name.setToolTip(name.text())
name.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DirOpenIcon))
date = QtGui.QStandardItem(date)
self.tv_model.appendRow([name, date])
#--------------------------------------------------------------------
def get_date(self, path):
return "a date"
#--------------------------------------------------------------------
def create_connections( self ):
self.tv_file_list.clicked.connect( self.on_click )
# slots --------------------------------------------------------------
def on_click(self, item ):
index = self.tv_file_list.selectedIndexes()[0]
item = self.tv_model.itemFromIndex(index).text()
print item
############################################
class MyModel(QtGui.QStandardItemModel):
def __init__(self, parent=None):
super(MyModel, self).__init__(parent)
#--------------------------------------------------------------------
def flags(self, index):
flag = QtCore.Qt.ItemIsEnabled
if index.isValid():
flag |= QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable
return flag
############################################
class File_List( QtGui.QTreeView ):
''' Create the file filters '''
def __init__( self, mainUIWindow, parent=get_parent() ):
super( File_List, self ).__init__( parent )
self.setModel(mainUIWindow.tv_model)
self.setIndentation(0)
self.setColumnWidth(0,500)
self.setFocusPolicy(QtCore.Qt.NoFocus)
self.setStyleSheet("QToolTip { color: rgb(170,170,170); background-color: rgb(20,20,20); border: 1px rgb(20,20,20); }")
############################################
if __name__ == "__main__":
# workaround for a bug in maya
try:
tree_view_ui.close()
tree_view_ui.deleteLater()
except:
pass
tree_view_ui = Main_Window()
tree_view_ui.show()
try:
tree_view_ui.show()
except:
tree_view_ui.close()
tree_view_ui.deleteLater()
SOLUTION:
Thanks to ekhumoro for the quick and easy solution!
Here's the updated code and a link to some HTML basics that helped me format the tooltip:
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import maya.OpenMayaUI as mui
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
''' Classes '''
############################################
class Main_Window( QtGui.QDialog ):
def __init__( self, parent=get_parent() ):
super( Main_Window, self ).__init__( parent )
self.create_gui()
self.create_layout()
self.create_connections()
self.get_contents()
#--------------------------------------------------------------------
def create_gui( self ):
self.tv_model=MyModel()
self.tv_file_list = File_List( self )
#--------------------------------------------------------------------
def create_layout( self ):
self.main_layout = QtGui.QVBoxLayout( self )
self.main_layout.addWidget( self.tv_file_list )
self.setLayout( self.main_layout )
#--------------------------------------------------------------------
def get_contents(self):
self.tv_model.clear()
self.tv_model.setHorizontalHeaderLabels(["name","date"])
contents=["path1","path2"]
for path in contents:
date = self.get_date(path)
self.add_file(path,date)
self.tv_file_list.setColumnWidth(0, 150)
#--------------------------------------------------------------------
def add_file(self, name, date):
name = QtGui.QStandardItem(name)
user_text = "Me"
image_path = "C:/windows/temp/image_01.png"
name.setToolTip('<b>{0}</b><br><img src="{1}">'.format(user_text, image_path))
name.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DirOpenIcon))
date = QtGui.QStandardItem(date)
self.tv_model.appendRow([name, date])
#--------------------------------------------------------------------
def get_date(self, path):
return "a date"
#--------------------------------------------------------------------
def create_connections( self ):
self.tv_file_list.clicked.connect( self.on_click )
# slots --------------------------------------------------------------
def on_click(self, item ):
index = self.tv_file_list.selectedIndexes()[0]
item = self.tv_model.itemFromIndex(index).text()
print item
############################################
class MyModel(QtGui.QStandardItemModel):
def __init__(self, parent=None):
super(MyModel, self).__init__(parent)
#--------------------------------------------------------------------
def flags(self, index):
flag = QtCore.Qt.ItemIsEnabled
if index.isValid():
flag |= QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable
return flag
############################################
class File_List( QtGui.QTreeView ):
''' Create the file filters '''
def __init__( self, mainUIWindow, parent=get_parent() ):
super( File_List, self ).__init__( parent )
self.setModel(mainUIWindow.tv_model)
self.setIndentation(0)
self.setColumnWidth(0,500)
self.setFocusPolicy(QtCore.Qt.NoFocus)
self.setStyleSheet("QToolTip { color: rgb(170,170,170); background-color: rgb(20,20,20); border: 1px rgb(20,20,20); }")
############################################
if __name__ == "__main__":
# workaround for a bug in maya
try:
tree_view_ui.close()
tree_view_ui.deleteLater()
except:
pass
tree_view_ui = Main_Window()
tree_view_ui.show()
try:
tree_view_ui.show()
except:
tree_view_ui.close()
tree_view_ui.deleteLater()
Tooltips accept rich-text, which means you can use any markup that is part of the Supported HTML Subset. This includes an img tag, so all you need is something like:
item.setToolTip('<b>%s</b><br><img src="%s">' % (filename, iconpath))

PySide: Instant tooltips (no delay before showing the tooltip)

The tool I'm building uses tooltips to display extra info about a file before you click on it. It would be great if someone could lend some insight into how to accomplish this. I'm about a month into PySide so I'm having trouble deciphering these advanced examples/answers I've found online, so a simple code example with some comments will help me out a lot.
Here's what I have so far. I have no idea what I'm doing when it comes to events, so this is the best I could do with the code examples I have:
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import maya.OpenMayaUI as mui
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
''' Classes '''
############################################
class Main_Window( QtGui.QDialog ):
def __init__( self, parent=get_parent() ):
super( Main_Window, self ).__init__( parent )
self.setMouseTracking(True) # Set tracking
self.create_gui()
self.create_layout()
self.create_connections()
self.get_contents()
self.shapeItems = []
#-------------------------------------------------------------------- # Mouse things
def mouseMoveEvent(self, event):
if (event.buttons() & QtCore.Qt.LeftButton):
self.moveItemTo(event.pos())
#-------------------------------------------------------------------- # Mouse things
def event(self, event):
if event.type() == QtCore.QEvent.ToolTip:
helpEvent = event
index = self.itemAt(helpEvent.pos())
if index != -1:
QtGui.QToolTip.showText(helpEvent.globalPos(), self.shapeItems[index].toolTip())
else:
QtGui.QToolTip.hideText()
event.ignore()
return True
return super(Main_Window, self).event(event)
#--------------------------------------------------------------------
def create_gui( self ):
self.tv_model=MyModel()
self.tv_file_list = File_List( self )
#--------------------------------------------------------------------
def create_layout( self ):
self.main_layout = QtGui.QVBoxLayout( self )
self.main_layout.addWidget( self.tv_file_list )
self.setLayout( self.main_layout )
#--------------------------------------------------------------------
def get_contents(self):
self.tv_model.clear()
self.tv_model.setHorizontalHeaderLabels(["name","date"])
contents=["path1","path2"]
for path in contents:
date = self.get_date(path)
self.add_file(path,date)
self.tv_file_list.setColumnWidth(0, 150)
#--------------------------------------------------------------------
def add_file(self, name, date):
name = QtGui.QStandardItem(name)
name.setToolTip(name.text())
name.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DirOpenIcon))
date = QtGui.QStandardItem(date)
self.tv_model.appendRow([name, date])
#--------------------------------------------------------------------
def get_date(self, path):
return "a date"
#--------------------------------------------------------------------
def create_connections( self ):
self.tv_file_list.clicked.connect( self.on_click )
# slots --------------------------------------------------------------
def on_click(self, item ):
index = self.tv_file_list.selectedIndexes()[0]
item = self.tv_model.itemFromIndex(index).text()
print item
############################################
class MyModel(QtGui.QStandardItemModel):
def __init__(self, parent=None):
super(MyModel, self).__init__(parent)
#--------------------------------------------------------------------
def flags(self, index):
flag = QtCore.Qt.ItemIsEnabled
if index.isValid():
flag |= QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable
return flag
############################################
class File_List( QtGui.QTreeView ):
''' Create the file filters '''
def __init__( self, mainUIWindow, parent=get_parent() ):
super( File_List, self ).__init__( parent )
self.setModel(mainUIWindow.tv_model)
self.setIndentation(0)
self.setColumnWidth(0,500)
self.setFocusPolicy(QtCore.Qt.NoFocus)
self.setStyleSheet("QToolTip { color: rgb(170,170,170); background-color: rgb(20,20,20); border: 1px rgb(20,20,20); }")
############################################
if __name__ == "__main__":
# workaround for a bug in maya
try:
tree_view_ui.close()
tree_view_ui.deleteLater()
except:
pass
tree_view_ui = Main_Window()
tree_view_ui.show()
try:
tree_view_ui.show()
except:
tree_view_ui.close()
tree_view_ui.deleteLater()
HERE is a post describing how to create instant tooltips, but without any code examples I'm at a loss for how to write this. The documentation wasn't really much of a help either (it really should have simple examples for beginners).
HERE is a code that shows how to implement mouse move events, but I haven't been able to get it to work in my own example above. I keep getting errors that say: "TypeError: super(type, obj): obj must be an instance or subtype of type" and "AttributeError: 'Main_Window' object has no attribute 'itemAt'"
Again, any help or thoughts would be great. Thank you
SOLUTION
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import maya.OpenMayaUI as mui
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
''' Classes '''
############################################
class Main_Window( QtGui.QDialog ):
def __init__( self, parent=get_parent() ):
super( Main_Window, self ).__init__( parent )
self.create_gui()
self.create_layout()
self.create_connections()
self.get_contents()
#--------------------------------------------------------------------
def create_gui( self ):
self.tv_model=MyModel()
self.tv_file_list = File_List( self )
self.tv_file_list.setMouseTracking(True) # Set mouse tracking
#--------------------------------------------------------------------
def create_layout( self ):
self.main_layout = QtGui.QVBoxLayout( self )
self.main_layout.addWidget( self.tv_file_list )
self.setLayout( self.main_layout )
#--------------------------------------------------------------------
def get_contents(self):
self.tv_model.clear()
self.tv_model.setHorizontalHeaderLabels(["name","date"])
contents=["path1","path2"]
for path in contents:
date = self.get_date(path)
self.add_file(path,date)
self.tv_file_list.setColumnWidth(0, 150)
#--------------------------------------------------------------------
def add_file(self, name, date):
name = QtGui.QStandardItem(name)
user = "me"
name.setToolTip("<b>{0}</b><br><b>{1}</b>".format(name.text(), user) ) # Here's where I set the tooltip
name.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DirOpenIcon))
date = QtGui.QStandardItem(date)
self.tv_model.appendRow([name, date])
#--------------------------------------------------------------------
def get_date(self, path):
return "a date"
#--------------------------------------------------------------------
def create_connections( self ):
self.tv_file_list.clicked.connect( self.on_click )
self.tv_file_list.entered.connect( self.handleItemEntered ) # New connection
# slots --------------------------------------------------------------
def on_click(self, item ):
index = self.tv_file_list.selectedIndexes()[0]
item = self.tv_model.itemFromIndex(index).text()
print item
#--------------------------------------------------------------------
def handleItemEntered(self, index): # New slot
if index.isValid():
QtGui.QToolTip.showText(
QtGui.QCursor.pos(),
index.data(),
self.tv_file_list.viewport(),
self.tv_file_list.visualRect(index)
)
############################################
class MyModel(QtGui.QStandardItemModel):
def __init__(self, parent=None):
super(MyModel, self).__init__(parent)
def flags(self, index):
flag = QtCore.Qt.ItemIsEnabled
if index.isValid():
flag |= QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable
return flag
############################################
class File_List( QtGui.QTreeView ):
''' Create the file filters '''
def __init__( self, mainUIWindow, parent=get_parent() ):
super( File_List, self ).__init__( parent )
self.setModel(mainUIWindow.tv_model)
self.setIndentation(0)
self.setColumnWidth(0,500)
self.setFocusPolicy(QtCore.Qt.NoFocus)
self.setStyleSheet("QToolTip { color: rgb(170,170,170); background-color: rgb(20,20,20); border: 1px rgb(20,20,20); }")
############################################
if __name__ == "__main__":
# workaround for a bug in maya
try:
tree_view_ui.close()
tree_view_ui.deleteLater()
except:
pass
tree_view_ui = Main_Window()
tree_view_ui.show()
try:
tree_view_ui.show()
except:
tree_view_ui.close()
tree_view_ui.deleteLater()
This is much easier to do using the treeview's entered signal. And if you use the overload of showText that takes a rect argument, QToolTip will automatically do the rest.
Here's a simple demo:
from PySide import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.view = QtGui.QTreeView(self)
self.view.setMouseTracking(True)
self.view.entered.connect(self.handleItemEntered)
model = QtGui.QStandardItemModel(self)
for text in 'One Two Three Four Five'.split():
model.appendRow(QtGui.QStandardItem(text))
self.view.setModel(model)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.view)
def handleItemEntered(self, index):
if index.isValid():
QtGui.QToolTip.showText(
QtGui.QCursor.pos(),
index.data(),
self.view.viewport(),
self.view.visualRect(index)
)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 200, 200)
window.show()
sys.exit(app.exec_())

Categories