Add new column to a QTableWidget - c++

I need to add a new column to an existing QTableWidget whenever a button is pressed, something like:
ui->tableWidget->addColumn();

The best way I could find was:
ui->tableWidget->setColumnCount(ui->tableWidget->horizontalHeader()->count() + 1);

column_index = self.table_name.columnCount()
self.table_name.setRowCount(1)
self.table_name.setColumnCount(column_index + 1)
self.tb_widget = QWidget()
picture = "C:\\Users\\usa\\Desktop\\test.png"
pixmap = QPixmap(picture).scaled(QSize(160, 90))
tb_item_img = QLabel()
tb_item_img.setPixmap(pixmap)
# tb_item_img.setFixedSize(160, 90)
tb_item_time = QLabel()
tb_item_time.setText("00:00:00")
self.tb_item_btb.setProperty('time', tb_item_time.text())
self.tb_item_btb.clicked.connect(self.clickTableCut)
self.table_name.setColumnWidth(column_index, 160)
self.table_name.setRowHeight(0, 90)
self.table_name.horizontalHeader().setSectionResizeMode(column_index, QtWidgets.QHeaderView.Fixed)
self.table_name.setCellWidget(0, column_index, self.tb_widget)
# click
def clickTableCut(self, ):
button = self.sender()
if button:
t = button.property('time')
print(t)
column_index = self.table_name.indexAt(button.pos()).column()
# if remove an item
self.table_name.removeColumn(column_index)

Related

Python TkInter delete childs's grid

How can I clear the grid into a canvas in Tkinter?
Actually i have this :
photoCanvas = Canvas(photoFrame,bg='#E5E7E9')
rowPhoto = 0
columnPhoto = 0
for i in range(0, len(listPhotos), 1):
panel = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200)
panel.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")
if columnPhoto < 3:
columnPhoto += 1
else:
rowPhoto += 1
columnPhoto = 0
And i want to delete all my buttons.
Thx
If you want to delete all widgets inside another widget -- such as all buttons in your canvas -- you can simply iterate over all of the children of the widget and call the destroy method.
For example:
for widget in photoCanvas.winfo_children():
widget.destroy()

How to deselect checkboxes using a button in python?

I need to have a button which clears selected check boxes. Please anyone guide me. Thanks in advance.
import Tkinter
from Tkinter import*
top = Tkinter.Tk()
CheckVar1=IntVar()
CheckVar2=IntVar()
C1=Checkbutton(top, text = "Music", variable = CheckVar1,
onvalue = 1, offvalue = 0, height=5,
width = 20,activebackground="red",bg="green")
C2=Checkbutton(top, text = "Video", variable = CheckVar2,
onvalue = 1, offvalue = 0, height=5,
width = 20)
C1.pack()
C2.pack()
B = Tkinter.Button(top, text ="Hello",activebackground="red",
,bd=3,bg="green",width=5) #Button
B.pack()
top.mainloop()
Create a function that will set the value of CheckVar1 and CheckVar2 to 0.
def clear():
CheckVar1.set(0)
CheckVar2.set(0)
And then just link it with the button.
B = Tkinter.Button(top, text ="Hello",activebackground="red",
bd=3,bg="green",width=5, command = clear) #Button
BTW, you had an extra comma here.

getting the value to the Entry using tkinter

I want to know how to display the values using Entry? i mean for instance if i have a function like:
def open():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
blue, green, red = cv2.split(path)
total = path.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
blue.set(B_mean1)
green.set(G_mean1)
red.set(R_mean1)
root = Tk()
blue_label = Label(app,text = 'Blue Mean')
blue_label.place(x = 850,y = 140)
blue = IntVar(None)
blue_text = Entry(app,textvariable = blue)
blue_text.place(x = 1000,y = 140)
green_label = Label(app,text = 'Green Mean')
green_label.place(x = 850,y = 170)
green = IntVar(None)
green_text = Entry(app,textvariable = green)
green_text.place(x = 1000,y = 170)
red_label = Label(app,text = 'Red Mean')
red_label.place(x = 850,y = 200)
red = IntVar(None)
red_text = Entry(app,textvariable = red)
red_text.place(x = 1000,y = 200)
button = Button(app, text='Select an Image',command = open)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 650, y = 60)
root.mainloop()
I have specified all the necessary imports and list variables. Still the value is not being displayed in the Entry field.
like if i get the value as :
blue mean = 37,
green mean = 36,
red mean = 41
and it will print in the console but not in the window. How can I achieve this?
Any suggestions are welcome!
Thanks for your supports!
Firstly I want to recommend that instead of using the place method you use the grid method. It is a lot faster and allows you to do things in a much more orderly fashion - especially in this application. Note that there are other geometry managers - like pack - which are good in yet other instances. Anyways, your GUI:
root = Tk()
blue_label = Label(root, text="Blue mean:")
blue_label.grid(row=1, column=1, sticky="w")
blue_entry = Entry(root)
blue_entry.grid(row=1, column=2)
green_label = Label(root, text="Green mean:")
green_label.grid(row=2, column=1, sticky="w")
green_entry = Entry(root)
green_entry.grid(row=2, column=2)
red_label = Label(root, text="Red mean:")
red_label.grid(row=3, column=1, sticky="w")
red_entry = Entry(root)
red_entry.grid(row=3, column=2)
root.mainloop()
That makes your GUI display nicely and without the manual geometry. Note that sticky just sets how the text is justified ("w" means west, and so the text justifies left).
Now, for actually displaying the text, all you have to do is:
blue_entry.insert(0, "blue-mean-value")
green_entry.insert(0, "green-mean-value")
red_entry.insert(0, "red-mean-value")
And if you are overwriting any text that is already there just do:
blue_entry.delete(0, END) # And green_entry and red_entry

How to connect Fl_Text_Editor with output which is prodeced by a function?

I have a function which produces column of numbers:
def distancesplit(self):
img = np.asarray(Image.open("testtwo.tif").convert('L'))
img = 1 * (img < 127)
areasplit = np.split(img.ravel(), 24) # here we are splitting converted to 1D array
for i in areasplit:
area = (i == 0).sum()
print area
I want to output "area" result on Fl_Text_Editor widget. Here is the code I have now:
window = Fl_Window(100,100,400,400) # creating FLTK window
window.label(sys.argv[0])
button = Fl_Button(9,20,180,50) # making button class instance
button.label("Compute area")
button.callback(pixelarea) # connecting button to the function
button_two = Fl_Button(9,80,180,50)
button_two.label("Compute distances")
button_two.callback(distancesplit)
button_three = Fl_Button(9,140,180,50)
button_three.label("Compute features")
button_three.callback(distancetwo)
textedit = Fl_Text_Editor(9, 220, 180, 50)
textedit.buffer(self.textbuffer)
textedit.label("Text Editor")
textbuffer = Fl_Text_Buffer()
textbuffer.text("Code is written by the emotionally unstable alien who had survived space aircraft collision")
window.end() # code for running FLTK construction of widgets
window.show(len(sys.argv), sys.argv)
Fl.run() Thank you

How can I change color of part of the text in QLineEdit?

I want to add some syntax highlighting to text being written in QLineEdit, but it does not support rich text formatting, I can not change QlineEdit to something else, so I should find how to set color of text in this widget.
Is there a way to do this?
Just found a neat trick for that.
static void setLineEditTextFormat(QLineEdit* lineEdit, const QList<QTextLayout::FormatRange>& formats)
{
if(!lineEdit)
return;
QList<QInputMethodEvent::Attribute> attributes;
foreach(const QTextLayout::FormatRange& fr, formats)
{
QInputMethodEvent::AttributeType type = QInputMethodEvent::TextFormat;
int start = fr.start - lineEdit->cursorPosition();
int length = fr.length;
QVariant value = fr.format;
attributes.append(QInputMethodEvent::Attribute(type, start, length, value));
}
QInputMethodEvent event(QString(), attributes);
QCoreApplication::sendEvent(lineEdit, &event);
}
static void clearLineEditTextFormat(QLineEdit* lineEdit)
{
setLineEditTextFormat(lineEdit, QList<QTextLayout::FormatRange>());
}
// Usage example:
QLineEdit* lineEdit = new QLineEdit;
lineEdit->setText(tr("Task Tracker - Entry"));
QList<QTextLayout::FormatRange> formats;
QTextCharFormat f;
f.setFontWeight(QFont::Bold);
QTextLayout::FormatRange fr_task;
fr_task.start = 0;
fr_task.length = 4;
fr_task.format = f;
f.setFontItalic(true);
f.setBackground(Qt::darkYellow);
f.setForeground(Qt::white);
QTextLayout::FormatRange fr_tracker;
fr_tracker.start = 5;
fr_tracker.length = 7;
fr_tracker.format = f;
formats.append(fr_task);
formats.append(fr_tracker);
setLineEditTextFormat(lineEdit, formats);
You can change the color with the use of style sheets.
QLineEdit* myLineEdit = new QLineEdit("Whatever");
//for whatever case you want to change the color
if(syntax_needs_to_highlighted)
myLineEdit->setStyleSheet("QLineEdit#myLineEdit{color:blue}");
You may want to consider using QTextBrowser for this case.
You can change color of texts like this:
QLineEdit *line = new QLineEdit();
line->setText("this is a test");
line->setStyleSheet("foreground-color: blue;");
If it won't work, replace the last line with the following:
line->setStyleSheet("color: blue;");
I was able to accomplish this by overlaying a QLabel on top of a QLineEdit then making the text color of the line edit white. When the textEdited signal is emitted, use it to update the text of the QLabel. The QLabel accepts rich text so you can process the text in the QLineEdit and replace key words with the HTML needed to display the text in the way you want it. I'm sure you could modify the code to change the text color of the current selection.
class LabelEditPair(QLineEdit):
"""
QLineEdit that changes the color of the word 'blue' to blue and
the changes the font weight of the word 'bold' to bold.
"""
def __init__(self):
super().__init__()
self.label = QLabel("starting out")
self.label.setParent(self)
self.label.move(3, 0)
self.label.setAttribute(Qt.WA_TransparentForMouseEvents)
self.setStyleSheet("QLineEdit{color: white}")
self.textEdited.connect(self.text_edited)
def resizeEvent(self, event):
self.label.setFixedHeight(self.height())
self.label.setFixedWidth(self.width())
super().resizeEvent(event)
def text_edited(self, text):
text = text.replace("blue", "<span style='color: blue'>blue</span>")
text = text.replace("bold", "<span style='font-weight: bold'>bold</span>")
self.label.setText(text)
EDIT
The previous example doesn't work well in instances where the text overflows from the QLineEdit widget. Here is a more comprehensive widget that uses the same idea but instead of making a subclass of QLineEdit the widget is a subclass of QFrame with a QLineEdit and two QLabels, one before the cursor and one after. The widget replaces regex matches with HTML to change the style of those characters.
class LabelEditPair(QFrame):
"""
QLineEdit that changes the color of the word 'blue' to blue and
the changes the font weight of the word 'bold' to bold.
"""
def __init__(self, initial_text: str):
super().__init__()
self.stylized_regex: List[Tuple[str, str]] = []
self.setFixedHeight(22)
self.setObjectName("frame")
self.setStyleSheet("QFrame#frame{background-color: white; border: 1px solid gray}"
"QFrame:hover#frame{border: 1px solid black}"
"QFrame:selected#frame{border: 1px solid blue}")
self.setFrameStyle(QFrame.Box)
self.line_edit = QLineEdit(initial_text)
self.line_edit.setParent(self)
self.line_edit.move(0, 2)
self.line_edit.setStyleSheet("border: 0px solid white; background-color:transparent")
self.line_edit.setFixedWidth(2**16)
self.left_label = QLabel()
self.left_label.setParent(self.line_edit)
self.left_label.move(1, 1)
self.left_label.setAlignment(Qt.AlignRight)
self.left_label.setAttribute(Qt.WA_TransparentForMouseEvents)
self.right_label = QLabel()
self.right_label. setParent(self.line_edit)
self.right_label.move(5, 1)
self.right_label.setAlignment(Qt.AlignLeft)
self.right_label.setAttribute(Qt.WA_TransparentForMouseEvents)
self.right_label.setFixedWidth(2**16)
self.offset = 0
self.line_edit.textEdited.connect(self.text_edited)
self.line_edit.cursorPositionChanged.connect(self.apply_shift)
self.line_edit.selectionChanged.connect(self.set_text_to_update)
self.update_text_needed = True
self.placeholder = ""
self.color = (0, 0, 0)
def text(self):
return self.line_edit.text()
def setReadOnly(self, read_only: bool):
self.line_edit.setReadOnly(read_only)
self.line_edit.setAttribute(Qt.WA_TransparentForMouseEvents, read_only)
self.line_edit.end(False)
def set_placeholder_text(self, text: str):
self.placeholder = text
def set_text_color(self, color: Tuple[int, int, int]):
self.color = color
def set_text_to_update(self):
self.update_text_needed = True
def text_edited(self, text: str):
if len(text) == 0:
self.left_label.setText(self.placeholder)
self.left_label.setStyleSheet("color: gray")
return
self.left_label.setStyleSheet(f"color: rbg{self.color}")
new = self.line_edit.cursorPosition()
left_text = text[:new]
right_text = text[new:]
self.left_label.setText(left_text)
self.right_label.setText(right_text)
for style, regex in self.stylized_regex:
matches = findall(regex, left_text)
for match in matches:
left_text = left_text.replace(match, f"<span style='{style}'>{match}</span>")
self.left_label.setText(left_text)
matches_right = findall(regex, right_text)
for match in matches_right:
right_text = right_text.replace(match, f"<span style='{style}'>{match}</span>")
self.right_label.setText(right_text)
self.update_text_needed = False
def add_style_for_regex(self, style: str, regex: str):
self.stylized_regex.append((style, regex))
def apply_shift(self, old=None, new=None):
text = self.line_edit.text()
rect = self.line_edit.cursorRect()
x_pos = rect.x()
if x_pos + self.offset > self.width() - 8 and new == old + 1:
self.offset = -1*(x_pos - (self.width()-8))
elif new + 1 == old and x_pos + self.offset < self.width() * 1/2:
self.offset += 5
self.offset = min(0, self.offset)
if len(text) == 0:
self.offset = 0
self.line_edit.move(self.offset, 2)
self.left_label.setFixedWidth(x_pos + 4)
self.right_label.move(x_pos + 5, 1)
if self.update_text_needed:
self.text_edited(text=text)
self.update_text_needed = True
example usage
self.color_edit = LabelEditPair("")
self.color_edit.add_style_for_regex("color: blue", "(?:HI|HELLO)")
main_layout.addWidget(self.color_edit)