Modify the sidebar and the title bar (if possible) to have this color: #F7F8FC Python 3.12 code: import sys
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QTableView, QFrame
)
from PySide6.QtGui import QStandardItemModel, QStandardItem, QFont
from PySide6.QtCore import QEvent, Qt
import sqlite3
def run_query(query, parameters=()):
with sqlite3.connect('media.db') as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables():
create_movies_table_sql = '''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
'''
create_series_table_sql = '''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
'''
run_query(create_movies_table_sql)
run_query(create_series_table_sql)
class MediaTracker(QMainWindow):
def init(self):
super().init()
code
Assistant
self.setWindowTitle("Movies and Series Tracker")
self.setGeometry(200, 100, 1000, 600)
# Create a QFont instance and set the desired font family and point size
font = QFont()
font.setPointSize(12)
font.setFamily('Literata') # Set the font family, delete to use default
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QHBoxLayout(self.main_widget)
# Sidebar with navigation buttons
self.sidebar_layout = QVBoxLayout()
self.main_layout.addLayout(self.sidebar_layout)
self.movies_button = QPushButton("Movies")
self.movies_button.setFont(font)
self.movies_button.clicked.connect(self.show_movies)
self.sidebar_layout.addWidget(self.movies_button)
self.series_button = QPushButton("Series")
self.series_button.setFont(font)
self.series_button.clicked.connect(self.show_series)
self.sidebar_layout.addWidget(self.series_button)
self.sidebar_layout.addStretch()
# Button bar area
self.button_bar = QFrame()
self.button_bar.setFixedWidth(50)
self.button_bar.setStyleSheet("background-color: white;")
self.main_layout.addWidget(self.button_bar)
# Content layout for the table
self.content_layout = QVBoxLayout()
self.main_layout.addLayout(self.content_layout)
self.setup_movie_table(font)
self.setup_series_table(font)
# '+' and '-' buttons for current row
self.plus_button = QPushButton("+", self.button_bar)
self.plus_button.setFont(font)
self.plus_button.setFixedSize(20, 20)
self.plus_button.setVisible(False)
self.plus_button.raise_()
self.plus_button.clicked.connect(self.add_entry)
self.minus_button = QPushButton("-", self.button_bar)
self.minus_button.setFont(font)
self.minus_button.setFixedSize(20, 20)
self.minus_button.setVisible(False)
self.minus_button.raise_()
self.minus_button.clicked.connect(self.delete_entry)
self.current_row_id = None
self.load_data()
self.show_movies()
# Connect model's dataChanged signal to a slot for saving changes
self.movies_model.dataChanged.connect(self.save_movie_changes)
self.series_model.dataChanged.connect(self.save_series_changes)
self.series_table = QTableView()
self.series_table.setFont(font)
self.series_table.setModel(self.series_model)
self.series_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.series_table.setMouseTracking(True)
self.series_table.viewport().installEventFilter(self)
self.series_table.hideColumn(0) # Hides the ID column
def load_data(self):
if self.movies_table.isVisible():
self.load_movie_data()
else:
self.load_series_data()
def load_movie_data(self):
self.movies_model.removeRows(0, self.movies_model.rowCount())
movies_data = run_query('SELECT * FROM movies')
if not movies_data:
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
movies_data = run_query('SELECT * FROM movies')
code
for row in movies_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.movies_model.appendRow(items)
def load_series_data(self):
self.series_model.removeRows(0, self.series_model.rowCount())
series_data = run_query('SELECT * FROM series')
if not series_data:
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
series_data = run_query('SELECT * FROM series')
code
for row in series_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.series_model.appendRow(items)
def delete_entry(self):
if self.current_row_id is not None:
if self.movies_table.isVisible():
run_query("DELETE FROM movies WHERE id = ?", (self.current_row_id,))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("DELETE FROM series WHERE id = ?", (self.current_row_id,))
self.load_series_data()
def clear_content(self):
for i in reversed(range(self.content_layout.count())):
widget_to_remove = self.content_layout.itemAt(i).widget()
self.content_layout.removeWidget(widget_to_remove)
if widget_to_remove is not None:
widget_to_remove.setParent(None)
def eventFilter(self, source, event):
if event.type() == QEvent.Type.MouseMove:
table = self.movies_table if self.movies_table.isVisible() else self.series_table
if source is table.viewport():
self.update_buttons_position(table, event.position().toPoint())
return super(MediaTracker, self).eventFilter(source, event)
def update_buttons_position(self, table, pos):
index = table.indexAt(pos)
if index.isValid():
row_index = index.row()
self.current_row_id = table.model().index(row_index, 0).data()
rect = table.visualRect(index)
run_query("UPDATE movies SET movie = ?, year = ?, present = ?, watched = ?, notes = ? WHERE id = ?",
(movie_data, year_data, present_data, watched_data, notes_data, id_data))
run_query("UPDATE series SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?, complete = ?, watched = ?, seasons_seen = ?, notes = ? WHERE id = ?",
(series_data, seasons_data, year_data, present_data, seasons_present_data, complete_data, watched_data, seasons_seen_data, notes_data, id_data))
def get_bool_value(self, item):
text = item.text().lower()
if text in ['true', '1']:
return True
elif text in ['false', '0']:
return False
return None
if name == "main":
app = QApplication(sys.argv)
create_tables()
tracker = MediaTracker()
tracker.show()
sys.exit(app.exec())
To modify the sidebar and the title bar to have the color #F7F8FC in your PySide6 application, follow the steps below.
1. Changing the Sidebar Background Color
In your current implementation, the sidebar is managed by a QVBoxLayout (self.sidebar_layout). To apply a background color, you need to encapsulate this layout within a QWidget and then apply a stylesheet to that widget.
Here's how you can modify your code to change the sidebar's background color:
python
# Inside the MediaTracker class __init__ method
# Replace the existing sidebar_layout and related code with the following:
# Create a QWidget for the sidebar
self.sidebar_widget = QWidget()
self.sidebar_widget.setStyleSheet("background-color: #F7F8FC;") # Set sidebar background color
# Create a QVBoxLayout for the sidebar
self.sidebar_layout = QVBoxLayout(self.sidebar_widget)
# Add the sidebar widget to the main layout
self.main_layout.addWidget(self.sidebar_widget)
# Continue adding buttons to the sidebar_layout as before
self.movies_button = QPushButton("Movies")
self.movies_button.setFont(font)
self.movies_button.clicked.connect(self.show_movies)
self.sidebar_layout.addWidget(self.movies_button)
self.series_button = QPushButton("Series")
self.series_button.setFont(font)
self.series_button.clicked.connect(self.show_series)
self.sidebar_layout.addWidget(self.series_button)
self.sidebar_layout.addStretch()
Explanation:
Create a QWidget for the Sidebar: Instead of adding the QVBoxLayout directly to the main_layout, create a QWidget (self.sidebar_widget) that will serve as the container for the sidebar.
Apply Stylesheet: Set the background color of self.sidebar_widget using setStyleSheet.
Set Layout: Assign the QVBoxLayout to self.sidebar_widget instead of the main widget.
Add to Main Layout: Add self.sidebar_widget to the main_layout.
This modification ensures that the entire sidebar (including all buttons) has the background color #F7F8FC.
2. Changing the Title Bar Background Color
Customizing the native title bar (the bar provided by the operating system) is not straightforward because it's managed by the OS and not directly controllable via Qt stylesheets. However, you can create a custom title bar within your application to achieve the desired look.
Here's a basic implementation of a custom title bar:
python
Explanation:
Frameless Window: self.setWindowFlags(Qt.FramelessWindowHint) removes the native title bar.
Custom Title Bar Widget: A new QWidget (self.title_bar) is created to act as the title bar. It's styled with the desired background color #F7F8FC.
Title Label and Close Button: Added a label for the window title and a close button styled to match the desired color.
Window Movement: Implemented mousePressEvent and mouseMoveEvent to allow the user to click and drag the window using the custom title bar.
Layout Adjustments: Changed the main layout to a QVBoxLayout to stack the custom title bar above the main content.
Note: Customizing the title bar can be quite involved, especially if you want to add functionality like minimize, maximize, and additional styling. The above example provides a basic implementation. For more advanced features, you might need to handle additional window states and interactions.
3. Complete Modified Code
Here's the complete modified code incorporating both changes (sidebar and custom title bar):
python
Key Points in the Modified Code:
Custom Title Bar: Implemented using a QWidget with a horizontal layout containing a title label and a close button. The title bar has the background color #F7F8FC.
Frameless Window: Removed the native title bar using Qt.FramelessWindowHint.
Window Movement: Enabled dragging the window by clicking and dragging the custom title bar.
Sidebar Styling: Encapsulated the sidebar within a QWidget and applied the background color #F7F8FC.
Layout Adjustments: Changed the main layout to a QVBoxLayout to stack the custom title bar above the main content area, which uses a QHBoxLayout for the sidebar, button bar, and content tables.
3. Additional Enhancements (Optional)
Minimize and Maximize Buttons: You can add additional buttons next to the close button to handle minimizing and maximizing the window.
Hover Effects and Icons: Enhance the aesthetics by adding hover effects or icons to the sidebar buttons and title bar buttons.
Responsive Design: Ensure that the custom title bar and sidebar are responsive to window resizing.
4. Final Notes
Custom Title Bars: Implementing a custom title bar means that you lose some native window functionalities, such as double-click to maximize, system menus, etc. You'll need to manually handle these if required.
Cross-Platform Consistency: Custom UI elements help in maintaining a consistent look across different platforms (Windows, macOS, Linux), but ensure thorough testing on all target platforms.
Further Customization: Explore Qt Stylesheets for more advanced styling options to enhance the look and feel of your application.
Feel free to adjust the styles and functionalities as per your requirements. Let me know if you need further assistance!